Daniel Lane
Daniel Lane

Reputation: 61

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?

Upvotes: 1

Views: 2520

Answers (2)

user207421
user207421

Reputation: 311052

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504132

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.

Upvotes: 9

Related Questions