继承类(Java),显式构造函数错误消息 [英] Inheritance classes (Java), explicit constructor error message
问题描述
所以我试图学习继承类.
so I am trying to learn about inheritance classes.
首先,我创建了一个名为Box的类来计算盒子的面积.
First I created a class called Box to calculate the area of the box.
然后,我创建了一个TestBox类,在其中创建了一个名为fedEx的框对象.
Then I created a TestBox Class in which I have created a box object called fedEx.
包装盒类:
public class Box {
private String boxName;
public void calculateArea(int length, int width) {
System.out.println("Area of " + getBoxInfo() + (length * width));
}
public Box(String boxName) {
this.boxName = boxName;
}
public String getBoxInfo() {
return boxName;
}
}
TestBox类:
public class TestBox {
public static void main(String[] args) {
Box fedEx = new Box("fedEx");
fedEx.calculateArea(23, 2);
}
}
到目前为止,如果我运行此代码,一切正常,并且打印屏幕显示Fedex 46的面积
So Far if I run this code everything works out fine and my print screen shows Area of Fedex 46
所以现在我去创建一个名为NewBox的新类,并使用扩展"继承Box类中的方法,该类用于计算Volume
So now I went to create a new class called NewBox and used "extends" to inherit the methods from the class Box, this class is used to calculate Volume
NewBox类:
public class NewBox extends Box {
public void calculateVolume(int length, int width, int height) {
System.out.println("Volume = " + (length * width * height));
}
}
现在要进行测试,我在TestBox类中创建了一个称为UPS的新对象,现在我的TestBox类如下所示:
Now to test this I created a new object in my TestBox class called UPS, now my TestBox class looks like this:
public class TestBox {
public static void main(String[] args) {
Box fedEx = new Box("fedEx");
fedEx.calculateArea(23, 2);
NewBox UPS = new NewBox("UPS");
UPS.calculateArea(3, 2);
UPS.calculateVolume(3, 2, 2);
}
}
当我尝试运行该程序时,出现以下错误消息:
When I try to run this program I get the following error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor NewBox(String) is undefined
at day3.inheritence.TestBox.main(TestBox.java:10)
我正在使用eclipse作为我的IDE.
I am using eclipse as my IDE.
我该如何解决我的代码,错误消息是什么意思?
What can I do to fix my code, and what does the error message mean?
推荐答案
NewBox必须具有一个转发给父类的构造函数的构造函数.试试这个:
NewBox has to have a constructor that forwards to the parent class's constructor. Try this:
public class NewBox extends Box{
public NewBox(String name) {
super(name);
}
public void calculateVolume(int length, int width, int height){
System.out.println("Volume = " + (length*width*height));
}
}
这篇关于继承类(Java),显式构造函数错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!