ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • day05 #클래스, 인스턴스 멤버
    JAVA/개념 2022. 2. 12. 21:55

     

    멤버 = 변수와 메소드



    클래스 영역 안에는 변수와 메소드만.(+변수에 초기값 대입)  - if for syso 등 x


    인스턴스 메소드(void)는 클래스 멤버에 접근할 수 있다.
    클래스 메소드(static void)는 인스턴스 멤버에 접근할 수 없다. 
    (클래스는 항상 인스턴스보다 먼저->아직 만들어지지 않은 인스턴스에 접근하려는 격)

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    class C1 {
        
        static int static_variable = 1;
        int instance_variable = 2;
        static void static_static() {
            System.out.println(static_variable);        //static to static : 가능
        }            
       static void static_instance() {
            System.out.println(instance_variable);        //static to instance : 불가능1
        }
        
        void instance_static() {
            System.out.println(static_variable);        //instance to static : 가능
        }
        void instance_instance() {
            System.out.println(instance_variable);        //instance to instance : 가능
        }
    public class Member {  
        public static void main(String[] args) {
            C1 c = new C1();
            c.static_static();                            //instance 이용해 static 메소드에 접근    -> 성공
            c.static_instance();                        //static 메소드가 instance 변수에 접근    -> 실패(불가능1)
            c.instance_static();                        //instance메소드가 정적 변수에 접근        ->성공
            c.instance_instance();                        //성공
            C1.static_static();                            //성공
            C1.static_instance();                        //실패
            C1.instance_static();                        //실패(클래스 입장에서는 아직 생성되지 않은 인스턴스메소드에 접근할 수 없음)
            C1.instance_instance();                        //실패(인스턴스 메소드는 아직 생성되지 않음)
        }
        
    }
    cs

     

     

     

     

    출처 : 수업+생활코딩 자바 입문(구버전)

    댓글

Designed by Tistory.