为什么 this() 和 super() 不能在构造函数中一起使用?

2022-09-01 03:02:39

为什么不能在构造函数中同时使用两者?this()super()

合并这样的东西的原因是什么?


答案 1

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(); //
  }
} 

现在,如果调用以下构造函数,则调用这些构造函数:new B(5)

     this( false);
A() ---------------> A(false)
^
|
| super(); 
|
|     this();
B() <--------------- B(5)  <--- you start here

更新

如果你能够使用,你最终可能会得到这样的东西: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

如您所见,您会遇到一个问题,即可以使用不同的参数调用构造函数,现在您必须以某种方式决定应该使用哪个。此外,其他构造函数( and ) 可能包含现在可能无法正确调用的代码(即无序等),因为调用将绕过它们,而不会。A(boolean)A()B()super( true )this()


答案 2

和 之间存在差异。super()this()

super()- 调用基类构造函数,而
- 调用当前类构造函数。this()

和 都是构造函数调用。
构造函数调用必须始终是第一个语句。所以你要么有或作为第一个陈述。this()super()super()this()


推荐