☕ 자바 JAVA/☕ 클래스와 함수 Class & Method

[JAVA]참조변수 super & 조상 생성자 super()

yeun.log 2024. 3. 27. 22:43
반응형

 

참조변수
super
public class Super {
    public static void main(String[] args) {
        ChildClass child = new ChildClass();
        child.method();
    }
}

class ParentClass {int x = 10; /* super.x */}

class ChildClass extends ParentClass {
    int x = 20; // this.x

    void method() {
        System.out.println("x=" + x);
        System.out.println("this.x" + this.x);
        System.out.println("super.x=" + super.x);
    }
}

출력결과

  • 객체 자신을 가리키는 참조변수. (this와 비슷)
  • 조상멤버와 자신멤버를 구별할 때 사용한다.
  • instance method(생성자) 내에서만 존재. -> static method에서 사용불가.

만약 자식클래스 ChildClass에 변수x가 없다면?
class ParentClass {int x = 10; /* super.x */}

class ChildClass extends ParentClass {
    void method() {
        System.out.println("x=" + x);
        System.out.println("this.x" + this.x);
        System.out.println("super.x=" + super.x);
    }
}

출력결과

상속된 부모class의 값을 this가 가져온다.

그래서 super와 this가 비슷하다는 거.

 


 

조상 생성자
super()
class Point2D {
    int x, y;

    Point2D(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class Point3dChild extends Point2D {
    int z;

    Point3dChild() {
        this(0, 0, 0);  // 생성자호출.
    }

    Point3dChild(int x, int y, int z) {
        super(x, y);    // 생성자호출. this.x와 같이 조상의 멤버를 자식class에서 초기화하는 것은 비권장.
        this.z = z;     // 자신의 멤버를 초기화.
    }
}
  • 조상의 생성자를 호출할 때 사용.
  • (생성자는 상속이 안되는 점 때문에) 조상의 멤버는 조상의 생성자를 호출해서 초기화.
  • 생성자의 첫 줄에 반드시 생성자를 호출해야 한다.
    -> 그렇지 않으면 compiler가 생성자의 첫줄에 super();를 삽입한다.
    -> 따라서 위의 코드에서 부모class에 있는 변수가 상속되어도 this.x = x;가 아니라
    super(매개변수)와 같이 적어준다. 어차피 super();가 compile시 만들어지니까.

가장 기본인 기본생성자
상속시 super() 등을 꼭 확인하자

 

 

반응형