[英]Java - Cannot find symbol constructor in sub class
我收到错误消息“找不到符号构造函数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;
}
}
创建派生对象时,请先调用超级构造函数。 如果不这样做,则调用默认构造函数。 在您的代码中,没有没有参数的默认构造函数,这就是对象构造失败的原因。 您需要提供一个不带参数的构造函数,或按如下所示调用现有的构造函数:
public Sphere(double radius, String color, boolean filled){
super(color, filled);
this.radius=radius;
}
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;
}
super
或者this
必须在每一个构造开始被称为-如果你不写,编译器会插入super()
默认情况下。
但是, GeometricObject
没有没有参数的构造函数。 如果不存在,则无法调用! 这意味着编译器也无法自动调用它。
您需要在Sphere的每个构造函数中使用Sphere
的颜色和填充度调用super
,如下所示:
public Sphere(String color, boolean filled){
super(color, filled);
}
public Sphere(double radius, String color, boolean filled){
super(color, filled);
this.radius=radius;
}
由于您的超类只有一个构造函数:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.