Reputation: 642
I tried to execute the below java code which demonstrates single inheritance.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width*height*depth;
}
}
class BoxWeight extends Box {
double mass;
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
mass = m;
}
}
class BoxDemo {
public static void main(String[] args) {
BoxWeight box = new BoxWeight(10,20,15,32.3);
double vol;
vol = box.volume();
System.out.println("Volume = " + vol);
}
}
But this raised the following error:
C:\User\Java>javac BoxWeight.java
BoxWeight.java:16: error: constructor Box in class Box cannot be applied to given types;
BoxWeight(double w, double h, double d, double m) {
^
required: double,double,double
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Again when I modified the code in sub class constructor as below
BoxWeight(double w, double h, double d, double m) {
super(w,h,d);
mass = m;
}
it gave the desired output.
Why the first way didn't work?
Upvotes: 0
Views: 104
Reputation: 1344
Always remember a simple rule when working with inheritance
Whenever any constructor of a child class is called the default constructor of the parent class is called automatically
Now in our case when we invoked BoxWeight(double w, double h, double d, double m)
constructor the default constructor of parent class i.e. Box()
needs to be called automatically. But in our case Box()
doesn't exist so we need to manually call super(w,h,d);
. Here super is used to refer to the parent class.
Upvotes: 1
Reputation: 393781
You have to pass the width, height and depth to the super class constructor:
BoxWeight(double w, double h, double d, double m) {
super(w,h,d);
mass = m;
}
When the sub-class constructor doesn't contain the super(...)
call to the super-class constructor, the compiler implicitly adds a super()
call to the super-class parameter-less constructor, which doesn't exist in your Box
class. That's the reason your code didn't pass compilation.
As Amongalen commented, if you don't define any constructor in your class, the compiler adds a default parameter-less constructor. However, once you define any constructor, the default constructor is not added. This means that your code could have passed compilation if you just removed the Box(double w, double h, double d)
constructor (or kept that constructor and added an explicit Box()
constructor).
Upvotes: 2