简体   繁体   中英

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?

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? 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.

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 .
  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.

You can see that by recursion when you call super() , step (2) precedes step (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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