Java

참조변수 super, 생성자 super()

성장코딩 2022. 12. 31. 02:08

Theme. 참조변수 super

 

객체 자신을 가리키는 참조변수.

인스턴스 메서드나 생성자 내에만 존재 ( static 메서드 내에서 사용불가 )

조상의 멤버를 자신의 멤버와 구별할 때 사용

 

cf) 참조변수 super vs this

super: 조상멤버, 자신멤버 구별

this: lv와 iv 구별

 

아래 코드를 살펴보자

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
package test;
 
class Parent {
    int x = 10;
    // super.x 지만 super.이 생략된 것
}
 
class Child extends Parent {
    int x = 20;
    // this.x 지만 this.이 생략된 것
    
    void method() {
        System.out.println("x = " + x); //가장 가까운 x는 this.x이므로 20이 출력됨
        System.out.println("this.x = " + this.x);
        System.out.println("super.x = " + super.x);
    }
    
}
 
public class MainClass {
 
    public static void main(String[] args) {
        Child c  = new Child();
        c.method();
        
    }
 
}
 
cs

 

Theme. 생성자 super()

 

super()는 조상의 생성자이다.

즉, 조상의 생성자를 호출할 때 사용한다.

조상의 멤버를 조상의 생성자를 호출해서 초기화할 수 있다.

( 상속 시 조상의 생성자, 초기화 블럭은 상속되지 않는다.)

 

아래 코드를 살펴보자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//2차원 좌표를 나타내는 Point 클래스
class Point {
    int x;
    int y;
    //생성자
    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
//Point 클래스를 부모 클래스로 상속 받는 자녀 클래스 Point3D
//3차원 좌표를 나타내는 Point3D 클래스
class Point3D extends Point {
    int z;
    //생성자
    Point3D (int x, int y, int z) {
        //this.x = x; --- X
        //this.y = y; --- X
        super(x, y); // 조상클래스의 생성자 Point(int x, int y)를 호출
        this.z = z; //자신의 멤버는 this로 초기화
    }
}
cs