Iva*_*nin -2 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();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,只要我尝试将参数传递给主类中的BoxWeight()构造函数,就会出现错误.
你要为它定义两个构造函数 BoxWeight
BoxWeight(BoxWeight object)
BoxWeight(double w, double h, double d, double wei)
Run Code Online (Sandbox Code Playgroud)
但尝试使用没有参数的一个
BoxWeight myBox1 = new BoxWeight();
Run Code Online (Sandbox Code Playgroud)
因此,您需要在构造对象时提供另一个实例,如下所示:
BoxWeight myBox1 = new BoxWeight(someOtherBox);
Run Code Online (Sandbox Code Playgroud)
或使用具有单独定义值的构造函数:
BoxWeight myBox1 = new BoxWeight(myWidth, myHeight, myDepth, myWeight);
Run Code Online (Sandbox Code Playgroud)
或者为您BoxWeight调用一个现有的no-args构造函数Box构造函数另一个没有参数的新构造函数.
BoxWeight() {
super(...)
}
Run Code Online (Sandbox Code Playgroud)
如果您习惯于在没有实际定义构造函数的情况下调用no-args构造函数,那么这是因为Java提供了一个默认构造函数,但只要您自己没有定义任何构造函数.有关详细信息,请参阅此页面.