Video in progress
What does this code print? What happens when an overridable method is called from a constructor?
class Base {
Base() { init(); }
void init() { }
}
class Child extends Base {
private final String name = "child";
private String label = "L";
@Override void init() { System.out.println(label); }
}
new Child();
It prints null. The Base constructor calls Child.init(), and at that moment Child's fields haven't been assigned yet. That's why you shouldn't call an overridable method from a constructor.
📖 Answer
Let's recall the order of object creation:
- Memory is allocated, and all fields have their default values (
null,0,false). - The
Child()constructor callssuper()first. - Inside
Base(),init()is called, and thanks to dynamic dispatch,Child.init()runs. - When
Base()finishes,Child's field initializers run (label = "L"). - The rest of the
Childconstructor runs.
init() runs in step 3, and label is assigned in step 4, so it's null.
An interesting point: if init() printed name, you'd get child. final String name = "child" is a compile-time constant, and the compiler replaces it directly with the value. If it were final but the value came from a method call, it would be null again.
How this shows up in real code:
- an abstract base class calls
validate()orregister(this)in its constructor; this"escapes" to another thread or a listener before it's fully constructed.
The rule: only call private, final or static methods from a constructor. If you need complex initialization, use a static factory or a separate init() (or @PostConstruct in Spring).
Sign up to mark studied questions and save your progress.