public Ex7_2 {
public static void main(String args[]) {
Child c = new Child();
c.method();
}
}
// 조상 클래스
class Parent {
int x = 10; // super.x
}
// 자손 클래스
class Child extends Parent {
int x = 20; // this.x
void method() {
System.out.println("x=" + x); // 20
System.out.println("this.x=" + this.x); // 20
System.out.println("super.x=" + super.x); // 10
}
}
public Ex7_3 {
public static void main(String args[]) {
Child2 c = new Child2();
c.method();
}
}
// 조상 클래스
class Parent2 {
int x = 10; // super.x와 this.x 둘 다 가능
}
// 자손 클래스
class Child2 extends Parent2 {
void method() {
System.out.println("x=" + x); // 10
System.out.println("this.x=" + this.x); // 10
System.out.println("super.x=" + super.x); // 10
}
}
조상의 생성자 super()
조상의 생성자를 호출할 때 사용
조상의 멤버는 조상의 생성자를 호출해서 초기화
생성자와 초기화 블럭은 상속되지 않는다.
class Point {
int x, 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) {
this.x = x; // 조상의 멤버를 초기화 -> 비추
this.y = y; // 조상의 멤버를 초기화 -> 비추
this.z = z; // 자신의 멤버를 초기화
}
// 추천
Point3D(int x, int y, int z) {
super(x, y); // 조상 클래스의 생성자 Point(int x, int y)를 호출
this.z = z; // 자신의 멤버를 초기화
}
}
생성자의 첫 줄에 반드시 생성자를 호출해야 한다. ex) super(), this()
그렇지 않으면 컴파일러가 생성자의 첫 줄에 super(); 를 삽입
class Point {
int x;
int y;
Point() {
this(0, 0);
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
--------- 컴파일 후 ---------
class Point extends Object {
int x;
int y;
Point() {
this(0, 0);
}
Point(int x, int y) {
super(); // Object();
this.x = x;
this.y = y;
}
}
예제
// 조상 클래스
class Point {
int x;
int y;
Point(int x, int y) {
// super(); // Object();
this.x = x;
this.y = y;
}
String getLocation() {
return "x: " + x + ", y: " + y;
}
}
// 자손 클래스
class Point3D extends Point {
int z;
Point3D(int x, int y, int z) {
// super(); // Point();
this.x = x;
this.y = y;
this.z = z;
}
// 오버라이딩
String getLocation() {
return "x: " + x + ", y: " + y + ", z: " + z;
}
}
// 메인 메서드
class PointTest {
// 🚩 컴파일 에러 발생
public static void main(String args[]) {
Point3D p3 = new Point3D(1, 2, 3);
}
}
컴파일 에러 발생 원인
생성자 Point3D(1, 2, 3);이 호출된다.
생성자의 첫 줄엔 반드시 생성자를 호출해야하므로 Point() 가 호출된다.
Point 클래스 내에 Point 기본 생성자가 없으므로 컴파일 에러가 발생한다.
Point3D(int x, int y, int z) {
// 조상의 생성자 Point(int x, int y)를 호출
super(x, y);
this.z = z;
}