1. super
- 자손클래스에서 조상클래스로부터 상속받은 멤버를 참조하는데 사용되는 참조변수이다.
- 맴버변수와 지역변수의 이름이 같을 때 this를 사용해서 구별하듯 상속받은 멤버와 자신의 클래스에 정의된 멤버의 이름이 같을 때는 super를 사용해서 구별 할 수 있다.
- 모든 인스턴스메서드에는 자신이 속한 인스턴스의 주소가 지역변수로 저장되는데 이것이 참조변수인 this와 super의 값이 된다.
- 참조변수와 메서드를 super를 써서 호출할 수 있다.
package com.tistory.gangzzang;
class SuperParent {
int x = 999;
} // SuperParent
class SuperChild extends SuperParent {
int x = 9999;
void method() {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("super.x = " + super.x);
}
} // SuperChild extends SuperParent
public class SuperTest {
public static void main(String[] args) {
SuperChild child = new SuperChild();
child.method();
}
} // SuperChild
/*
* 결과
*
* x = 9999
* this.x = 9999
* super.x = 999
*/
2. super()
- this()와 같은 클래스의 다른 생성자를 호출하는 데 사용되지만, super()는 조상 클래스의 생성자를 호출하는데 사용된다.
- 자손클래스의 인스턴스를 생성하면, 자손의 멤버와 조상의 멤버가 합쳐진 하나의 인스턴스가 생성된다.
- 조상의 멤버들도 초기화 되어야 하기 떄문에 자손클래스의 생성자의 첫 문장에서 조상의 생성자를 호출해야한다.
- 모든 클래스의 생성자는 첫 줄에 반드시 자신의 다른 생성자 또는 조상의 생성자를 호출해야한다. 그렇지 않으면 컴파일러는 생성자의 첫줄에 'super();'를 자동적으로 추가한다.
class Super2 {
int a = 111, b = 222;
Super2(int a, int b) {
super();
this.a = a;
this.b = b;
} // Super2 생성자
} // Super2
class Super2_3D extends Super2 {
int c = 333;
Super2_3D() {
this(1000, 2000, 3000); // Super2_3D(int a, int b, int c) 호출
}
Super2_3D(int a, int b, int c) {
super(a, b); // Super2(int a, int b) 호출
this.c = c;
}
}
public class SuperTest2 {
public static void main(String[] args) {
Super2_3D super2 = new Super2_3D();
System.out.println("super2.a = " + super2.a);
System.out.println("super2.b = " + super2.b);
System.out.println("super2.c = " + super2.c);
} // main
} // SuperTest2
/*
* 결과
*
* super2.a = 1000
* super2.b = 2000
* super2.c = 3000
*/
'Java > Java SE' 카테고리의 다른 글
| Java 다형성(polymorphism), instanceof 연산자 (0) | 2013.08.07 |
|---|---|
| Java 제어자(modifier), 접근 제어자(access modifier) (0) | 2013.08.06 |
| Java 오버라이딩(overriding) (0) | 2013.08.05 |
| Java 상속(inheritance) (0) | 2013.08.05 |
| Java 배열(array) (0) | 2013.08.04 |