Search code examples
javaconstructorsubclasssuperclass

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?


Solution

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