Bab*_*loo 33 java inheritance constructor
为什么不能this()
和super()
这两个一起在构造函数中使用?
合并这样的东西的原因是什么?
Tho*_*mas 37
this(...)
将在同一个类中调用另一个构造函数,而super()
将调用一个超级构造函数.如果super()
构造函数中没有,则编译器将隐式添加一个.
因此,如果两者都被允许,你最终可能会super
两次调用构造函数.
示例(不要在参数中查找):
class A {
public A() {
this( false );
}
public A(boolean someFlag) {
}
}
class B extends A {
public B() {
super();
}
public B( boolean someFlag ) {
super( someFlag );
}
public B ( int someNumber ) {
this(); //
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果调用,则调用new B(5)
以下构造函数:
this( false);
A() ---------------> A(false)
^
|
| super();
|
| this();
B() <--------------- B(5) <--- you start here
Run Code Online (Sandbox Code Playgroud)
更新:
如果你能够使用this()
,super()
你最终会得到这样的东西:
(注意:这是为了表明可能出现的问题,如果你被允许这样做 - 幸运的是你没有)
this( false);
A() ---------------> A(false)
^ ^
| |
| super(); | super( true ); <--- Problem: should the parameter be true or false?
| |
| this(); |
B() <--------------- B(5) <--- you start here
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,您遇到的问题是A(boolean)
可以使用不同的参数调用构造函数,现在您必须以某种方式决定应该使用哪个.另外,其他构造函数(A()
和B()
)可能包含现在可能无法正确调用的代码(即乱序等),因为调用super( true )
将绕过它们而this()
不会.
super()
和之间有区别this()
.
super()
- 调用基类构造函数,而
this()
- 调用当前类构造函数.
这两个this()
和super()
是构造函数调用.
构造函数调用必须始终是第一个语句.所以我们不能将两个语句作为第一个语句,因此我们可以调用super()
或者可以this()
从构造函数调用,但不能同时调用两个语句.