[英]Java Inheritance error: Implicit Super Constructor is undefined
I am a novice to Java and just learning OOP concepts. 我是Java的新手,只是学习OOP概念。 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;
}
}
You are receiving this error because BoxSuper does not have a no-arg constructor. 您收到此错误,因为BoxSuper没有no-arg构造函数。 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. 在BoxSub中构造函数调用期间,如果没有定义超级构造函数,则调用Java尝试自动调用no-arg super()构造函数。
Either define a super constructor call in BoxSuper like so: 在BoxSuper中定义一个超级构造函数调用,如下所示:
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: 或者在BoxSuper中定义一个无参数的构造函数:
class BoxSuper
{
int height;
int length;
int width;
BoxSuper(){}
...
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: 在你的情况下,解决方案是显式调用相应的超级构造函数作为你的Box的构造函数的第一行,如果你考虑它,这也很有意义,因为你想用a,b和c初始化super,就像写的那样在它的构造函数中:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.