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