Video in progress

Strong Junior 🧱 OOP and SOLID

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:

  1. new Derived() runs the Derived() constructor, whose first job is super();
  2. inside Base(), init() is called. It is a virtual call, so Derived.init() runs;
  3. at that moment the Derived fields hold only their default values: prefix == null. So value = null;
  4. after super() finishes, Derived's initializers run: prefix = "ID-". value stays null.

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, final or static methods from a constructor;
  • in a class meant for extension, document this restriction or move the initialization into a factory method.