iozee
iozee

Reputation: 1349

Final field initialization in a subclass

Strange, but I can't find a duplicate for this question. I have a superclass with overrideMe() method and a subclass that overrides it. Is the final field really initialized before the subclass constructor is called? As I can see from the output, it is.

Here's the output: Superclass constr str value: someValue Subclass constr str value: someValue

Could you please explain this to me? I thought that instance variables are initialized within the constructor call but not before it.

Here's the code:

public class Test {
  public Test() {
    System.out.println("Superclass constr");
    overrideMe();
  }

  public void overrideMe() {
  }
}

class Ext extends Test {
  private final String str = "someValue";

  public Ext() {
    System.out.println("Subclass constr");
  }

  @Override
  public void overrideMe() {
    System.out.println("str value: " + str);
  }

  public static void main(String[] args) {
    Ext test = new Ext();
    test.overrideMe();
  }
}

EDIT: if I declasre str field as non-final, the subclass call of it in the constructor returns null as I expect.

Upvotes: 2

Views: 2574

Answers (2)

Adrian Liu
Adrian Liu

Reputation: 385

The final field with initializer will be replaced with the const string by compiler, that's why it seemed the field is initialized even before the super constructor returned.

If the final field is blank inited, which means it is inited in the child class's constructor, then of course the super constructor will see a null.

If the field is neither final nor static, and an initializer is provided, then it will be inited after the super constructor and before the child constructor.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382112

Yes fields are initialized before the constructor is called, and this starts with the upper class before the overloading one.

Here's a general presentation : http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ306_014.htm

Upvotes: 2

Related Questions