Video in progress

Strong Middle ☕ Core Java

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:

  1. Memory is allocated, and all fields have their default values (null, 0, false).
  2. The Child() constructor calls super() first.
  3. Inside Base(), init() is called, and thanks to dynamic dispatch, Child.init() runs.
  4. When Base() finishes, Child's field initializers run (label = "L").
  5. The rest of the Child constructor 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() or register(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).