(Java) super() - 조상의 생성자

Jayden·2023년 3월 6일

Java

목록 보기
21/35
  • 조상 클래스의 생성자를 호출할 때 사용한다.
  • 조상의 멤버는 조상의 생성자를 호출해서 초기화
public class Ex7_4 {
	public static void main(String[] args) {
		Point3D p = new Point3D(1, 2, 3);
		System.out.println("x=" + p.x + ",y=" + p.y + ",z=" + p.z);
	}
}

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) {
		super(x, y); // 조상클래스의 생성자 Point(int x, int y)를 호출
		this.z = z;  // 자신의 멤버를 초기화
	}
}

- " 생성자의 첫 줄에 반드시 생성자를 호출해야 한다 "
그렇지 않으면 컴파일러가 생성자의 첫 줄에 super()를 삽입한다.

0개의 댓글