so I am trying to learn about inheritance classes.
First I created a class called Box to calculate the area of the box.
Then I created a TestBox Class in which I have created a box object called fedEx.
Box Class:
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 Class:
public class TestBox {
public static void main(String[] args) {
Box fedEx = new Box("fedEx");
fedEx.calculateArea(23, 2);
}
}
So Far if I run this code everything works out fine and my print screen shows Area of Fedex 46
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 Class:
public class NewBox extends Box {
public void calculateVolume(int length, int width, int height) {
System.out.println("Volume = " + (length * width * height));
}
}
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)
I am using eclipse as my IDE.
What can I do to fix my code, and what does the error message mean?
NewBox has to have a constructor that forwards to the parent class's constructor. Try this: