반응형
super는 자식 클래스에서 부모 클래스로 부터 상속받은 멤버를 참조하는데 사용되는 참조변수
- 멤버변수와 지역변수의 이름이 같을 때 this를 붙여서 구별
- 상속받은 멤버와 자신의 멤버와 이름이 같을 때 super를 붙여서 구별
- 모든 인스턴스 메서드에는 this와 super가 지역변수로 존재하는데 자신이 속한 인스턴스 주소가 자동으로 저장된다.
- 조상의 멤버와 자신의 멤버를 구별하는데 사용하는 점만 제외하면 this와 super 근본적으로 같다.
public class Point {
int x = 20;
}
class Circle extends Point{
int x = 10;
void method(){
System.out.println(x);
System.out.println(this.x);
System.out.println(super.x);
}
}
/* 출력
10
10
20
*/
class Circle extends Point{
void method(){
System.out.println(x);
System.out.println(this.x);
System.out.println(super.x);
}
}
//여기서는 상속받은 멤버변수 x가 출력되니까 출력 20,20,20 나온다.
super() - 부모의 생성자
this() 처럼 super() 도 생성자 이다.
- this() 같은 클래스의 다른 생성자 호출하는데 사용한다.
- super() 부모의 생성자를 호출하는데 사용한다.
public class Point {
int x;
int y;
Point(int x, int y){
this.x = x;
this.y = y;
}
}
class Circle extends Point{
int z;
Circle(int x,int y, int z){
super(x,y);
this.z = z;
}
}
클래스 자신에 선언된 변수는 자신의 생성자가 초기화를 책임지도록 작성하는 것이 좋다. (생성자는 상속 안된다.)
반응형
'책 > Java의 정석' 카테고리의 다른 글
[java] import문 (0) | 2023.02.04 |
---|---|
[java] 패키지(package) (0) | 2023.02.04 |
[java] 오버로딩 오버라이딩 (0) | 2023.02.04 |
[java] 상속 (extends) (0) | 2023.02.04 |
[java] 생성자(constructor)와 this, this() (2) | 2023.02.03 |