[英]incorrect constructor in Java child class
Can someone please help me understand why (in Java) class B is correct, while class C throws a compiling error? 有人可以帮助我了解为什么(在Java中)类B是正确的,而类C却引发了编译错误吗?
class A {
int x = 1;
A(int x) { this.x = x; }
}
class B extends A {
B() { super(2); }
B(int x) { super.x = x; } //Error
}
class C extends A {
C() { super.x = 2; } //Error
C(int x) { super.x = x; } //Error
}
Because in the Constructor C()
the Constructor A()
is called - implicitly. 因为在构造函数C()
,构造函数A()
被隐式调用。 You cannot prevent that, except by calling another constructor. 您不能阻止这种情况,除非调用另一个构造函数。 But the constructor A()
does not exist, just A(int)
, thus error. 但是构造函数A()
不存在,仅存在A(int)
,因此是错误的。 (The default constructor only exists implicitly if you didn't write ANY other constructor - as soon as you have another constructor, you must add the default constructor or it won't exist). (默认构造函数仅在未编写任何其他构造函数的情况下隐式存在-一旦拥有另一个构造函数,则必须添加默认构造函数,否则默认构造函数将不存在)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.