我收到错误“找不到符号构造函数GeometricObject()” 由于半径和高度不在超类中,我不能在Sphere()构造函数中使用super()。
public class Sphere extends GeometricObject{
private double radius;
public Sphere(){
}
public Sphere(double radius){
this.radius=radius;
}
public Sphere(double radius, String color, boolean filled){
this.radius=radius;
setColor(color);
setFilled(filled);
}
这是超级课程 公共类GeometricObject {
private String color = "white";
private boolean filled;
public GeometricObject(String color, boolean filled){
this.color=color;
this.filled=filled;
}
public String getColor(){
return color;
}
public void setColor(String color){
this.color=color;
}
public boolean isFilled(){
return filled;
}
public void setFilled(boolean filled){
this.filled=filled;
}
public String toString(){
return "Color: "+color +" and filled: "+filled;
}
}
答案 0 :(得分:1)
创建派生对象时,首先调用超级构造函数。如果不这样做,则调用默认构造函数。在您的代码中没有没有参数的默认构造函数,这就是对象构造失败的原因。 您需要提供不带参数的构造函数,或者调用现有的构造函数,如下所示:
public Sphere(double radius, String color, boolean filled){
super(color, filled);
this.radius=radius;
}
答案 1 :(得分:0)
public Sphere(double radius, String color, boolean filled){
this.radius=radius;
setColor(color);
setFilled(filled);
}
如上所述,这种隐含性调用super();
,它对应于GeometricObject()
,它不存在。将其更改为:
public Sphere(double radius, String color, boolean filled){
super(color, filled);
this.radius=radius;
}
答案 2 :(得分:0)
super
或this
- 如果您不编写它,编译器将插入super()
默认情况下。
但是,GeometricObject
没有不带参数的构造函数。如果它不存在,你就无法调用它!这意味着编译器也无法自动调用它。
您需要在super
的每个构造函数中使用球体的颜色和填充调用Sphere
,如下所示:
public Sphere(String color, boolean filled){
super(color, filled);
}
public Sphere(double radius, String color, boolean filled){
super(color, filled);
this.radius=radius;
}
答案 3 :(得分:0)
因为你的超类只有一个构造函数:
public GeometricObject(String color, boolean filled)
你需要在你的子类的构造函数中调用它:
public Sphere(){
super(?, ?); // but you don't know what values to specify here so you might have to use defaults
}
public Sphere(double radius){
super(?, ?); // but you don't know what values to specify here so you might have to use defaults
this.radius=radius;
}
public Sphere(double radius, String color, boolean filled){
super(color, filled);
this.radius=radius;
setColor(color); // you can get rid of this
setFilled(filled); // and this, since the super constructor does it for you
}