超类的构造函数

时间:2013-07-07 21:20:44

标签: java inheritance constructor super

您好我正在尝试从扩展其超类及其构造函数的类中实例化一个对象但是在实例化对象的构造函数中接受Java接受参数很难,有人可以帮助我,谢谢您!这是该计划:

public class Box {

    double width;
    double height;
    double depth;

    Box(Box ob)
        {
            this.width=ob.width;
            this.height=ob.height;
            this.depth=ob.depth;           
        }
    Box(double width, double height, double depth)
        {
            this.width=width;
            this.height=height;
            this.depth=depth;
        }

    double volume()
        {
            return width * height * depth;
        }


}


public class BoxWeight extends Box{

    double weight;
    BoxWeight(BoxWeight object)
        {
            super(object);
            this.weight=object.weight;
        }
    BoxWeight(double w, double h, double d, double wei)
        {

            super(w,h,d);
            this.weight=wei;
        }

}


public class Proba {


    public static void main(String[] args) {

        BoxWeight myBox1 = new BoxWeight();
        BoxWeight myBox2 = new BoxWeight();

    }
}

现在,只要我尝试将参数传递给主类中的BoxWeight()构造函数,就会出现错误。

1 个答案:

答案 0 :(得分:5)

您为BoxWeight

定义了两个构造函数
BoxWeight(BoxWeight object)
BoxWeight(double w, double h, double d, double wei)

但尝试使用不带参数的

BoxWeight myBox1 = new BoxWeight();

因此,您需要在构造对象时提供另一个实例,如下所示:

BoxWeight myBox1 = new BoxWeight(someOtherBox);

或使用具有单独定义值的构造函数:

BoxWeight myBox1 = new BoxWeight(myWidth, myHeight, myDepth, myWeight);

或为BoxWeight定义一个no-args构造函数,它可以调用现有的Box构造函数之一,也可以调用另一个没有参数的新构造函数。

BoxWeight() {
    super(...)
}

如果您习惯于在没有实际定义的情况下调用no-args构造函数,那么这是因为Java提供了默认构造函数,但只要您自己没有定义任何构造函数。有关详细信息,请参阅this page