隐式超级构造函数Shape2D()未定义。关于;包括Java.awts.Color“;
我正在处理一个项目,该项目给出了这样一个错误:“隐式超级构造函数Shape2D未定义。必须显式调用另一个构造函数”,但我并不真正理解 这是我的形体课隐式超级构造函数Shape2D()未定义。关于;包括Java.awts.Color“;,java,implicit,explicit,Java,Implicit,Explicit,我正在处理一个项目,该项目给出了这样一个错误:“隐式超级构造函数Shape2D未定义。必须显式调用另一个构造函数”,但我并不真正理解 这是我的形体课 import java.awt.Color; import java.lang.Comparable; abstract class Shape implements Comparable<Shape>{ private final int id; private final String name; priv
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
中扩展Shape
类时,Shape2D的
构造函数中,如果您没有指定,java隐式调用超类的构造函数。因此,目前上述代码如下所示
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、名称、描述、颜色)代码>在其他构造函数中,但始终可以使用Shape2D(高度、宽度)
构造函数创建新实例。在这种情况下,Java需要确保调用父类构造函数。谢谢,在您的帮助下,我能够弄清楚如何显式调用我的另一个构造函数。答案是将变量包含在非默认构造函数中,然后使用super
Shape2D(height , width){
super(1,"triangle","test",Color.yellow); //Called parent class's constructor.
this.height = height;
this.width = width;
}