- 자바의 정석 (기본편)을 참고했습니다.
- 복습을 위한 게시글입니다.
- 소스에 오타가 있을 수 있습니다. ^^:;
참조변수 super
super는 자손이 조상으로부터 상속받은 멤버를 참조하는데 사용되는 변수
멤버변수와 지역변수의 이름이 같을 때 this로 구별했듯이, 상속받은 멤버와 자신의 멤버가 이름이 같을 때 super로
구별할 수 있다.
참조변수 super 사용 코드 예제
class Ex7_2 {
public static void main(String args[]) {
// 인스턴스 생성 시 조상의 멤버도 함께 생성
Child c = new Child();
c.method();
}
}
// 조상 클래스 Parent
Class Parent {
int x = 10;
}
// Parent를 상속받는 자손 클래스 Child
Class Child extends Parent {
int x = 20;
void method() {
System.out.println("x="+x);
System.out.println("this.x="+this.x);
System.out.println("super.x="+super.x);
}
}
/*
결과
x=20
this.x=20
super.x=10
*/
class Ex7_3 {
public static void main(String args[]) {
// 인스턴스 생성 시 조상의 멤버도 함께 생성
Child c = new Child();
c.method();
}
}
// 조상 클래스 Parent
Class Parent {
int x = 10;
}
// Parent를 상속받는 자손 클래스 Child
Class Child extends Parent {
void method() {
System.out.println("x="+x);
System.out.println("this.x="+this.x);
System.out.println("super.x="+super.x);
}
}
/*
결과
x=10
this.x=10
super.x=10
*/
Child 클래스는 Parent 클래스를 상속받는데, 자신의 멤버 x와 조상의 멤버 x의 이름이 같기 때문에 구별이 힘들다.
때문에 참조변수 super을 사용해 자신의 멤버와 조상의 멤버를 구별하는 것이다.
예제 7_3을 확인해보면 this.x / super.x의 값이 똑같은 것을 확인할 수 있는데, x, this.x, super.x 모두 같은 변수를
의미하기 때문이다. 즉, this와 super는 근본적으로 같다.
조상의 생성자 super()
this()는 다른 클래스의 생성자를 호출하는데 사용되는데, super()는 조상 클래스의 생성자를 호출하는데 사용한다.
조상의 멤버는 조상의 생성자를 통해 초기화되도록 작성하는 것이 바람직하다.
생성자 super() 사용 예제 코드
class Ex7_4 {
public static void main(String args[]) {
Point3D p = new Point3D();
System.out.println("x="+p.x+",y="+p.y+",z="+p.z);
}
}
class Point {
int x;
int 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()로 호출 > 초기화
super(x,y);
this.z = z;
}
}
/*
결과
x=1, y=2, z=3
*/
'JAVA' 카테고리의 다른 글
[JAVA 복습] 다형성(Ploymorphism) (0) | 2021.09.02 |
---|---|
[JAVA 복습] 캡슐화와 접근 제어자 (0) | 2021.09.02 |
[JAVA 복습] 상속에 대해 (0) | 2021.09.02 |
[JAVA 복습] 생성자 this() 와 객체 자신을 가리키는 참조변수 this (0) | 2021.08.31 |
[JAVA 복습] 기본 생성자와 매개변수가 있는 생성자 (0) | 2021.08.31 |