Reputation: 44041
In the code below, myString is always initialized to null. I have to manually initialize in an init() or similar. As far as I can tell it is related to superclass/subclass but I don't understand the exact mechanism
public class A extends B {
private String myString = "test";
public static void main(String[] args) {
new A();
}
public A() {
super();
}
public void c() {
System.out.println(myString);
}
}
public class B {
public B() {
c();
}
public void c() {
}
}
Upvotes: 0
Views: 552
Reputation: 81
Thinking in Java Second Edition by Bruce Eckel, Behavior of polymorphic methods inside constructors (p. 337-339).
Upvotes: 0
Reputation: 46395
Add a call to c();
overidden method right after the object has been fully created and call to superclass constructor is done.
Change your code to this ..
public class A extends B {
private String myString = "test";
public static void main(String[] args) {
new A();
}
public A() {
super();
c(); // Include the call to c(); here ...
}
public void c() {
System.out.println(myString);
}
}
public class B {
public B() {
}
public void c() {
}
}
// Output : test
Upvotes: 0
Reputation: 39177
The issue with your code is, that myString
is initialized at the begin of the constructor of class A
but right after the super constructor (i.e. class B
). Since you access the variable before from the constructor of class B
(indirectly via call to overriden methode c
) your get this behaviour.
As a rule of thumb: if you want to avoid unexpected behavior do not call overriden methods before the constructor has been executed.
Upvotes: 3