简体   繁体   English

超级构造函数调用

[英]Super constructor call

In Java, if my class extends a super class and by default the first line of the constructor is Super() , are the fields of the super class initialized, or is just the constructor run? 在Java中,如果我的类扩展了一个超类,并且默认情况下,构造函数的第一行是Super() ,那么超类的字段是否已初始化,或者仅构造函数在运行?

Also, if the constructor in the superclass calls a method that happens to be in both classes, does it run the super class or sub class version? 另外,如果超类中的构造函数调用了恰好在两个类中的方法,那么它是否运行超类或子类版本?

In Java, if my class extends a super class and by default the first line of the constructor is Super(), are the fields of the super class initialised? 在Java中,如果我的类扩展了超类,并且默认情况下构造函数的第一行是Super(),那么超类的字段是否已初始化? or is just the constructor run? 还是只是构造函数运行?

The fields of the superclass are always initialized prior to the superclass constructor body running. 超类的字段始终在超类构造函数主体运行之前初始化。

See section 15.9.4 and section 12.5 of the JLS for details. 有关详细信息,请参见JLS的15.9.4节12.5节

Also, if the constructor in the superclass calls a method that happens to be in both classes, does it run the super class or sub class version? 另外,如果超类中的构造函数调用了恰好在两个类中的方法,那么它是否运行超类或子类版本?

Assuming the subclass method actually overrides the superclass one, the subclass implementation will be called. 假设子类方法实际上覆盖了超类一,则将调用子类实现。 This is generally seen as a Bad Thing, as it means the method can't rely on anything initialized by the subclass constructor. 通常将其视为坏事,因为这意味着该方法不能依赖子类构造函数初始化的任何内容。

the fields of the super class initialized, or is just the constructor run? 初始化超类的字段,还是仅运行构造函数?

It's the same thing. 这是同一件事。 The following things happen when a constructor is called: 调用构造函数时,会发生以下事情:

  1. The superclass constructor is called, unless the current class is java.lang.Object . 除非当前类为java.lang.Object ,否则将调用超类构造函数。
  2. The instance variable declarations with initializers and any anonymous initializers { } are executed. 执行带有初始化程序和任何匿名初始化程序{ }的实例变量声明。
  3. The code in the constructor following the (implicit or explicit) super() call is executed. (隐式或显式) super()调用之后的构造函数中的代码将被执行。

You can see that by recursion when you call super() , step (2) precedes step (3). 您可以在调用super()时通过递归看到,步骤(2)在步骤(3)之前。 So yes, the instance variables are initialized and the constructor code is executed. 因此,是的,实例变量已初始化构造函数代码已执行。

Also, if the constructor in the superclass calls a method that happens to be in both classes, does it run the super class or sub class version? 另外,如果超类中的构造函数调用了恰好在两个类中的方法,那么它是否运行超类或子类版本?

The subclass version. 子类版本。 Note that this is different from C++ where the object is viewed as partially constructed, ditto the v-table, so the superclass version will be run. 请注意,这与C ++有所不同,在C ++中,对象被视为部分构造,与v-table,因此将运行超类版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM