Java/Java

Java 09. this 와 super

shin96bc 2022. 3. 10. 10:09

(1) this
     1) 정의
          <1> 자신의 '객체' or '생성자'를 가리키는 '대명사'

     2) Case
          <1> 지역변수와 이름이 같은 멤버변수를 해당 지역에서 접근할 때
          <2> 자신의 객체를 다른 클래스에게 넘길 때
          <3> 자신의 생성자를 호출할 때

          ex) class B {
                    int age;
                    B() {
                         this(20); //(3) 
                    }
                    B(int age) {
                         this.age = age; //(1)
                         new BUser(this).use(); //(2)
                    }
                    void m() {
                         System.out.println("m의 age " + age);
                    }
                    public static void main(String[] args) {
                         new B();
                    }
               }

               class BUser {
                    B b;
                    BUser(B b) {
                         this.b = b;
                    }
                    void use() {
                         System.out.println("b.age: " + b.age); //멤버
                         b.m(); //메소드
                    }
               }


(2) super
     1) 정의
          <1> 부모의 '객체' or '생성자'를 가리키는 '대명사'

     2) Case
          <1> 부모의 생성자를 호출할 때
          <2> 오버라이딩되기전의 부모메소드를 호출할 때
          <3> 이름이 동일한 부모의 멤버를 호출할 때
          ex) class C {
                    String name = "홍길동";
                    C() {
                         super(); // (1) 모든 객체는 Object 의 자식이므로 extends Object 가 생략되어있다.
                    }
                    void m() { //오버라이딩 전 
                         System.out.println("C의 m()");
                    }
               }


               class CChild extends C{
                    String name = "이순신";
                    CChild(){
                         super.m(); // (2) 이렇게 호출하면 오버라이딩 전의 메소드 즉, 부모의 메소드를 부를 수 있다.
                         System.out.println("name: " +super.name);  // (3) 호출 되는건 부모의 전역변수 name 이다. 
                    }
                    void m(){ //오버라이딩 후 
                         System.out.println("CChild의 m()");
                    }
                    public static void main(String[] args) {
                         new CChild();
                    } 
               }