我正在一个项目中出现此错误“隐式超级构造函数Shape2D未定义。必须显式调用另一个构造函数”,但并没有真正理解。
这是我的形体课
import java.awt.Color;
import java.lang.Comparable;
abstract class Shape implements Comparable<Shape>{
private final int id;
private final String name;
private final String description;
private Color color;
//abstract method
abstract double area();
abstract double perimeter();
//get and set and non-abstract method
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
//non default constructor
public Shape(int id, String name, String description, Color color) {
this.id = id;
this.name = name;
this.description = description;
this.color = color;
}
@Override
public int compareTo(Shape o) {
return 0;
}
@Override
public String toString() {
return String.format("%s,%s,%s,%s",id,name,description,color);
}
}
这是我的Shape2D类,将提供width和height变量
import java.awt.Color;// this is where the problem occur. if i remove it, the abstract class has an error " Implicit super constructor Shape() is undefined for default constructor. Must define an explicit
constructor and Implicit super constructor Shape() is undefined. Must explicitly invoke another constructor"
abstract class Shape2D extends Shape {
public final double height;
public final double width;
Shape2D(height , width){
this.height = height;
this.width = width;
}
public Shape2D(int id, String name, String description, Color color) {
super(id, name, description, color);
}
}
我有一个超级班
在扩展Shape
中的Shape2D
类时,如果未指定,则Java从Shap2D's
构造函数隐式调用超类的构造函数。因此,当前上面的代码将如下所示,
Shape2D(height , width){
super(); //this line will automatically added, when code complies.
this.height = height;
this.width = width;
}
因为在父类Shape
中,您没有任何args构造函数。它不会找到任何合适的构造函数,并且会如您所提到的那样给出错误。为了避免这种情况,您可以明确提及要调用的超类的构造函数。因此,代码如下所示:
Shape2D(height , width){
super(1,"triangle","test",Color.yellow); //Called parent class's constructor.
this.height = height;
this.width = width;
}
您在其他构造函数中使用了super(id, name, description, color);
,但始终可以使用Shape2D(height , width)
构造函数创建一个新实例。在这种情况下,Java需要确保父类构造函数被调用。