[英]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.