JAVA
[JAVA]Implicit super constructor Point43() is undefined. Must explicitly invoke another constructor
한바다주인공
2025. 5. 11. 13:31
✅ 모든 생성자는 첫줄에 다른 생성자를 호출한다.
class Point43 {
int x;
int y;
Point43(int x, int y) {
this.x = x;
this.y = y;
}
String getLocation() {
return "x :"+x+", y :"+y;
}
}
class Point4D extends Point43{
int z;
Point4D(int x, int y, int z){
this.x =x;
this.y =y;
this.z = z;
}
@Override
String getLocation() {
return "x:"+x+",y:"+y+"z:"+z;
}
}
✔️ 위와 같은 코드 작성 시 "Point4D(int x, int y, int z)" 에 빨간줄이 그어졌다.
🚫 오류 내용은 암시적 슈퍼생성자 Point43()이 정의되지 않았습니다. 다른 생성자를 명시적으로 호출해야 합니다.
Implicit super constructor Point43() is undefined. Must explicitly invoke another constructor
위 작성된 코드에서 class Point{ 에서는 extends Object가 생략되어 있다. 자바에서 부모가 없는 클래스는 자동적으로 Object 클래스를 상속받는다. 그래서 Object클래스를 상속받는 내용이 없기에
Point(int x, int y){
super(); // Objcet();
this.x = x;
this.y = y; } 와 같이 super() 조상의 생성자가 생략되어 있다. 자바의 규칙 모든 생성자는 첫줄에 다른 생성자를 호출해야 함!
이미 위에서 기본생성자를 불러왔기 때문에 컴파일러 에러가 발생하였다.
위 코드를 아래와 같이 수정하면 에러가 사라진다!
class Point43 {
int x;
int y;
Point43(int x, int y) {
this.x = x;
this.y = y;
}
String getLocation() {
return "x :"+x+", y :"+y;
}
}
class Point4D extends Point43{
int z;
Point4D(int x, int y, int z){
super(x,y);
this.z = z;
}
@Override
String getLocation() {
return "x:"+x+",y:"+y+"z:"+z;
}
}
📌 즉, this.x = x; this.y =y ; 를 삭제하고 super(x,y);를 입력하여 호출하니 조상생성자는 조상님이 해주세요라고 호출하니 에러 는 사라진 셈이다!!!