부모 클래스로부터 상속받은 필드나 메소드를 자식 클래스에서 참조하는 데 사용하는 참조 변수(this와 비슷)
this 키워드 : 인스턴스 변수의 이름과 지역 변수의 이름이 같을 경우, 이를 구분을 위해 사용
super 키워드 : 부모 클래스의 멤버와 자식 클래스의 멤버 이름이 같을 경우, 이를 구별하기 위해 사용
class Test {
public static void main(String[] args) {
Child c = new Child();
c.method();
}
}
class Parent {
int x = 10;
int y = 100;
}
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
System.out.println("y = " + y); // y = 100
System.out.println("this.y = " + this.y); // this.y = 100
System.out.println("super.y = " + super.y); // super.y = 100
}
}
조상의 생성자를 호출할 때 사용
class Point {
int x, y;
Point() {
this(0, 0)
}
Point(int x, int y) {
//super(); => Object(); 컴파일러가 자동 추가
this.x = x;
this.y = y;
}
}
class Point3D extends Point {
int z;
Point3D() {}
// Point3D(int x, int y, int z) { // 자신의 생성자는 자신의 멤버만 초기화하는 것을 권장
// this.x = x;
// this.y = y;
// this.z = z;
// }
Point3D(int x, int y, int z) { // 생성자 super() 이용
super(x, y); // 조상클래스의 생성자 Point(int x, int y)를 호출
this.z = z; // 자신의 멤버를 초기화
}
}