为什么this()和super()都不能在构造函数中一起使用? [英] why can't this() and super() both be used together in a constructor?

查看:202
本文介绍了为什么this()和super()都不能在构造函数中一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why can't this() and super() both be used together in a constructor?

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

What is the reason for incorporating such a thing?

推荐答案

this(...)将调用同一个类中的另一个构造函数,而 super()将调用一个超级构造函数。如果构造函数中没有 super(),则编译器将隐式添加一个。

this(...) will call another constructor in the same class whereas super() will call a super constructor. If there is no super() in a constructor the compiler will add one implicitly.

因此如果两者都被允许,你最终可能会两次调用 super 构造函数。

Thus if both were allowed you could end up calling the super constructor twice.

示例(不要在参数中查找):

Example (don't look for a sense in the parameters):

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)调用以下构造函数:

Now, if you call new B(5) the following constructors are invoked:

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

更新

如果你能够使用 this() super()你最终会得到这样的结果:

If you were able to use this() and super() you could end up with something like this:

注意:这是为了显示可能出现的问题,如果你被允许这样做 - 幸运的是你没有这样做)

(Attention: this is meant to show what could go wrong, if you were allowed to do that - which you fortunately aren't)

     this( false);
A() ---------------> A(false)
^                    ^
|                    |
| super();           | super( true ); <--- Problem: should the parameter be true or false? 
|                    |
|     this();        |
B() <--------------- B(5)  <--- you start here

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

As you can see, you'd run into a problem where the A(boolean) constructor could be invoked with different parameters and you'd now have to somehow decide which should be used. Additionally the other constructors (A() and B()) could contain code that now might not get called correctly (i.e. out of order etc.) since the call to super( true ) would circumvent them while this() wouldn't.

这篇关于为什么this()和super()都不能在构造函数中一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆