Video in progress
What does this code print, and why is it dangerous to call an overridable method inside a constructor?
class Base {
Base() { init(); }
void init() { }
}
class Derived extends Base {
private String prefix = "ID-";
private String value;
@Override
void init() { value = prefix; }
public static void main(String[] args) {
System.out.println(new Derived().value);
}
}
It prints null. When the Base constructor calls init(), polymorphism makes Derived.init() run, but at that moment Derived's field initializers haven't run yet, so prefix is still null.
📖 Answer
The order, step by step:
new Derived()runs theDerived()constructor, whose first job issuper();- inside
Base(),init()is called. It is a virtual call, soDerived.init()runs; - at that moment the
Derivedfields hold only their default values:prefix == null. Sovalue = null; - after
super()finishes,Derived's initializers run:prefix = "ID-".valuestaysnull.
In prod, a bug like this often shows up later, somewhere else, as a NullPointerException.
Another trap: if value were also declared with an initializer (private String value = "default";), then in step 4 it would overwrite the value init() wrote.
An interesting nuance: if prefix were final and assigned a literal, it would become a compile-time constant and the compiler would inline it into the method, so it would print ID-. That is why bugs like this sometimes "fix themselves" and then come back after a small change.
The rules (Effective Java says the same):
- call only
private,finalorstaticmethods from a constructor; - in a class meant for extension, document this restriction or move the initialization into a factory method.
Sign up to mark studied questions and save your progress.