问题描述
请告诉我以下代码中的问题?
Can you please tell me the problem in following code?
class boxdemo1 {
public static void main(String args[]) {
boxweight weightbox = new boxweight(2, 3, 5, 4);
System.out.println(weightbox.volume());
}
}
class boxinfo {
int l, b, h;
/*
* boxinfo() { l=b=h=-1; }
*/
boxinfo(int a, int b, int c) {
l = a;
this.b = b;
h = c;
}
int volume() {
return l * b * h;
}
}
class boxweight extends boxinfo {
int w;
boxweight(int a, int b, int c, int w) {
l = a;
this.b = b;
h = c;
this.w = w;
}
}
当我编译它时,它显示以下错误:
类boxinfo中的构造函数boxinfo不能应用于给定类型;需要
:int,int,int; found:无参数;实际和形式参数列表的长度不同。
When I compile it,it shows following error:"constructor boxinfo in class boxinfo cannot be applied to given types;required:int,int,int; found:no arguments; actual and formal argument lists differ in length."
但是当我编译它包括被注释的代码(即boxinfo()构造函数)时,它会被编译。为什么需要包含默认构造函数?
But when I compile it including the code which is commented(i.e. boxinfo() constructor), it gets compiled. Why is it necessary to include default constructor?
推荐答案
通过设置 boxinfo(int a,int b ,int c)
构造函数,java为 boxinfo
设置的默认无参数构造函数被删除。然后,当你调用 boxweight(int a,int b,int c,int w)
构造函数时,因为 boxweight
class继承自 boxinfo
,你隐式调用 boxinfo
中的默认构造函数,它刚被覆盖。
By setting your boxinfo(int a, int b, int c)
constructor, the default no-parameters constructor set by java for boxinfo
gets deleted. Then, when you call the boxweight(int a,int b,int c,int w)
constructor, since the boxweight
class inherits from boxinfo
, you're implicitly calling the default constructor from boxinfo
which just got overrided.
为了避免这种情况,要么在 boxinfo
中创建一个无参构造函数,要么显式调用 super( a,b,c)
in boxweight
To avoid this, either create yourself a no-argument constructor in boxinfo
or call explicitly super(a, b, c)
in boxweight
这篇关于用Java中的构造函数继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!