Java/객체지향

참조변수 super

태감새 2022. 12. 23. 10:35

참조변수 super

super는 참조변수 this와 비슷하게 작동한다.

1. 조상의 생성자를 호출하는 경우 super()

2. 자손 클래스에서 조상 클래스로부터 상속받은 멤버를 참조하는 경우 super

 

하나씩 살펴보자

1. 조상의 생성자를 호출하는 super()

class Point{
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
class Point3D extends Point {
    int z;

    public Point3D(int x, int y, int z) {
        super(x, y);
        this.z = z;
    }
}

 

Point3D 클래스가 Point 클래스를 상속받은 상황이다.

생성자는 상속되지 않으므로 Point3D 클래스의 생성자를 만들어야 한다. 

Point3D 클래스는 조상 클래스를 포함하고 있으므로 Point 클래스의 생성자를 정의해야 한다.

이때 조상의 생성자를 지칭하는 함수가 super()이다. 

Point 클래스의 생성자는 매개변수 int형 2개가 필요하므로 super(x,y)의 형태로 작성하였다.

 

여기서 Point3D를 상속받는 클래스는 super의 매개변수가 몇개가 될까?

class Point4D extends Point3D{
    int k;

    public Point4D(int x, int y, int z, int k) {
        super(x, y, z);
        this.k = k;
    }
}

 

Point3D 생성자의 매개변수를 다 입력해야 하므로 x,y,z 총 3개이다.

2. 조상으로부터 상속받은 멤버를 참조하는 super

멤버 변수를 this로 지칭했다면 조상 클래스의 멤버는 super를 붙여서 구분한다.

class Point{
    int x = 1;
}
class Point3D extends Point {
    int x = 2;

    void function(){
        System.out.println(x);
        System.out.println(this.x);
        System.out.println(super.x);
    }

}
public class Main {
    public static void main(String[] args) {
        Point3D a = new Point3D();
        a.function();
    }
}

 

조상 클래스의 x는 1, 자손 클래스는 2를 입력했다.

출력 결과는 2,2,1 이다.

x와 this.x는 Point3D 클래스의 멤버변수 x를 지칭하고 super.x는 Point 클래스의 x를 가리키기 때문이다.

'Java > 객체지향' 카테고리의 다른 글

제어자 (modifier)  (0) 2022.12.24
패키지 (package)  (2) 2022.12.23
참조변수 this  (0) 2022.12.23
오버라이딩 (Overriding)  (0) 2022.12.23
상속과 포함  (0) 2022.12.22