본문 바로가기

Java의 정석

참조변수 super

참조변수 super

자손 클래스에서 조상 클래스로부터 상속받은 멤버를 참조하는 데 사용되는 참조변수.

 

멤버변수와 지역변수의 이름이 같을 때 this를 붙여서 구별했듯이 상속받은 멤버가 자신의 멤버와 이름이 같을 때는 super를 붙여서 구별할 수 있다.

public class superExample {
    public static void main(String[] args) {
        Child c = new Child();
        c.method();
    }
}

class Parent { int x = 10; }

class Child extends Parent {
    int x = 20;

    void method() {
        System.out.println("x : " + x); // x : 20
        System.out.println("this x : " + this.x); // this x : 20
        System.out.println("super x : " + super.x); // super x : 10
    }
}

위의 코드에서 Child 클래스는 Parent 클래스를 상속받는데 자신의 멤버인 x와 비슷한 이름인 x 또한 상속받는다. 때문에 super를 사용하여 구분한다.

 

package superEx;

public class superExample2 {
    public static void main(String[] args) {
        Child2 c = new Child2();
        c.method();
    }
}

class Parent2 { int x = 10; }

class Child2 extends Parent2 {

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

모든 인스턴스 메서드에는 this와 super가 지역변수로 존재하는데 자신이 속한 인스턴스의 주소가 자동으로 저장된다. 조상의 멤버와 자신의 멤버를 구별하는 데 사용된다는 점만 제외하면 근본적으로 같다.

 

this()처럼 super() 또한 생성자로 this()는 같은 클래스의 다른 생성자를 호출하는 데 사용되고 super()는 조상의 생성자를 호출하는데 사용된다.

package superEx;

public class superConstructor {
    public static void main(String[] args) {
        Point3D p = new Point3D(1, 2, 3);
        System.out.println("x : " + p.x + ", y : " + p.y + ", z : " + p.z); // x : 1, y : 2, z : 3
    }
}

class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y; // 같은 클래스의 다른 생성자 초기화
    }
}

class Point3D extends Point {
    int z;

    Point3D(int x, int y, int z) {
        super(x, y); // Point(int x, int y) 호출, 조상의 멤버를 초기화
        this.z = z;
    }
}

 

'Java의 정석' 카테고리의 다른 글

import  (0) 2022.04.04
패키지(Package)  (0) 2022.04.01
오버라이딩(overriding)  (0) 2022.03.30
Object 클래스  (0) 2022.03.29
단일 상속(single inheritance)  (0) 2022.03.28