Reputation: 13534
I am a novice to Java and just learning OOP concepts. Please review my code. I am getting the following error.- Implicit Super Constructor is undefined.
class BoxSuper
{
int height;
int length;
int width;
BoxSuper(BoxSuper obj)
{
height=obj.height;
length=obj.length;
width=obj.width;
}
BoxSuper(int a,int b,int c)
{
height=a;
length=b;
width=c;
}
BoxSuper(int val)
{
height=length=width=val;
}
int volume()
{
return height*length*width;
}
}
class BoxSub extends BoxSuper
{
int weight;
BoxSub(int a,int b,int c,int d)
{
height=a;
length=b;
width=c;
weight=d;
}
}
Upvotes: 3
Views: 19268
Reputation: 11113
You are receiving this error because BoxSuper does not have a no-arg constructor. During your constructor call in BoxSub, if you do not define the super constructor call Java tries to automatically call the no-arg super() constructor.
Either define a super constructor call in BoxSuper like so:
class BoxSub extends BoxSuper
{
int weight;
BoxSub(int a,int b,int c,int d)
{
super(a, b, c);
weight=d;
}
}
or define a no-arg constructor in BoxSuper:
class BoxSuper
{
int height;
int length;
int width;
BoxSuper(){}
...
Upvotes: 11
Reputation: 285403
A constructor always calls the super constructor, always. If no explicit call to the super constructor is made, then the compiler tries to set it up so that it will call the default parameter-less constructor. If a default parameter-less constructor doesn't exist, a compilation error as you're seeing is shown and compilation will fail.
The solution in your case is to explicitly call the appropriate super constructor as the first line of your Box's constructor, and this makes perfect sense too if you think about it since you want to initialize the super with a, b, and c just as written in its constructor:
class BoxSub extends BoxSuper
{
int weight;
BoxSub(int a,int b,int c,int d)
{
super(a, b, c);
// height=a;
// length=b;
// width=c;
weight=d;
}
}
Upvotes: 7