在我的java程序中有2个编译错误。澄清请

时间:2013-11-17 04:23:33

标签: java constructor

我得到的错误是 1 a找不到符号错误

2“构造函数圈,在类圈中不能应用于给定的类型。”

此时我似乎可以理解我做错了什么。

 public class Circle {
     private double radius;

     public Circle (double radius) {
         radius = radius;
     }      

     public double getRadius() {
         return radius;
     }

     public double getArea() {
         return radius * radius * Math.PI;
     }
}

class B extends Circle {
    private double length;

    B (double radius, double length) {
        Circle (radius);
        length = length;
    }

    //**override getArea()*/
    public double getArea() { 
        return getArea() * length;
    }
}

2 个答案:

答案 0 :(得分:1)

在超级Circle使用this来引用当前实例。

 public Circle (double radius) {
     this.radius = radius;// Use this
 } 

在子类中使用super()来访问超类构造函数。改变

B (double radius, double length) {
Circle (radius);// This is compilation error.
length = length;
}

B (double radius, double length) {
super(radius); // This is the way to access super-clss constructor.
this.length = length; //Use this to refer current instance length.
}

答案 1 :(得分:0)

我建议你改变:

radius = radius;

this.radius = radius; // 'this' makes reference to the actual instance

B构造函数更改为:

public Test(double radius, double length)
{
    super(radius); // Calls super class constructor
    this.length = length;
}