JAVA

객체지향 super() - 조상의 생성자

연93 2022. 9. 26. 10:29

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

생성자의 첫 줄에 반드시 생성자를 호출해야 한다.

그렇지 않으면 컴파일러가 생성자의 첫 줄에 super():를 삽입

클래스를 만들때 기본생성자 작성은 필수

class Point extends Object{
	int y;
	int x;
	
	Point(){
		this(0,0);
	}
	
	Point(int x, int y){
		super();  // Object 첫줄위치 컴파일 자동추가
		this.x = x;
		this.y = y;
	}
}