Video in progress

Strong Junior ☕ Core Java

What does this code print, and why?

class Parent {
    static { System.out.println("parent static"); }
    { System.out.println("parent instance"); }
    Parent() { System.out.println("parent ctor"); }
}
class Child extends Parent {
    static { System.out.println("child static"); }
    { System.out.println("child instance"); }
    Child() { System.out.println("child ctor"); }
}
public class Main {
    public static void main(String[] args) { new Child(); }
}

parent static, child static, parent instance, parent ctor, child instance, child ctor. First the classes are loaded (parent, then child) and their static blocks run. Then, when the object is created, each class runs its instance initializer first and its constructor after, going from parent to child.

📖 Answer

The output:

parent static
child static
parent instance
parent ctor
child instance
child ctor

Why it goes this way:

  1. Class initialization happens once, on first use. The parent class is initialized before the child. Static fields and static blocks run in the order they appear in the file.
  2. Object creation: the Child() constructor calls super() first.
  3. At each class level: the instance fields and { } blocks (in the order they're written), then the constructor body.

If new Child() is called a second time, the static lines don't print again.

There's an even worse trap in practice: calling an overridable method from the parent constructor. The child class's fields aren't initialized yet, and the method sees null or 0. Only call private or final methods from a constructor.