Java - 在子 class 中找不到符号构造函数

Java - Cannot find symbol constructor in sub class

我遇到错误 "cannot find symbol constructor GeometricObject()" 由于半径和高度不在 super class 中,我无法在 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);
    }

这就是超级class public class 几何对象{

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){
    this.radius=radius;
    setColor(color);
    setFilled(filled);
}

如所写,此隐式调用 super();,对应 GeometricObject(),后者不存在。将其更改为:

public Sphere(double radius, String color, boolean filled){
    super(color, filled);
    this.radius=radius;
}

superthis 必须在每个构造函数的开头调用 - 如果你不写它,编译器将插入 super()默认。

但是,GeometricObject 没有不带参数的构造函数。如果它不存在,你就不能调用它!这意味着编译器也不能自动调用它。

您需要在 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;
}

因为你的超级 class 只有一个构造函数:

public GeometricObject(String color, boolean filled)

您需要在子class的构造函数中调用它:

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
}

创建派生对象时首先调用超构造函数。如果不这样做,将调用默认构造函数。在您的代码中没有不带参数的默认构造函数,这就是对象构造失败的原因。 您需要提供一个不带参数的构造函数,或者调用现有的构造函数,如下所示:

public Sphere(double radius, String color, boolean filled){
  super(color, filled);
  this.radius=radius;
}