所以我试着学习继承类。
首先,我创建了一个名为box的类来计算该框的面积。
然后我创建了一个TestBox类,在其中我创建了一个名为fedEx的box对象。
盒类:
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);
}
}到目前为止,如果我运行这段代码,一切正常,我的打印屏幕显示联邦快递46的区域。
因此,现在我创建了一个名为NewBox的新类,并使用“扩展”继承了类Box中的方法,这个类用于计算卷
NewBox类:
public class NewBox extends Box {
public void calculateVolume(int length, int width, int height) {
System.out.println("Volume = " + (length * width * height));
}
}为了测试这一点,我在我的TestBox类中创建了一个名为TestBox的新对象,现在我的TestBox类如下所示:
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);
}
}当我试图运行这个程序时,我会收到以下错误消息:
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。
我能做些什么来修复我的代码,错误信息意味着什么?
发布于 2015-06-15 05:12:52
NewBox必须有一个向父类的构造函数转发的构造函数。试试这个:
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));
}
}发布于 2015-06-15 05:10:09
在NewBox类中添加以下内容。
public NewBox(String name){
super(name);
}现在NewBox变成
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));
}
}发布于 2015-06-15 05:18:12
由于父类(Box)有一个参数化构造函数,您的子类( NewBox )必须有一个参数化构造函数,然后这个构造函数应该调用其超级constructor.So,在NewBox类中添加下面的构造函数
public NewBox(String name){
super(name)
}https://stackoverflow.com/questions/30837715
复制相似问题