Video in progress

What does the following code print, and why in exactly this order?

class A { A() { System.out.println("A konstruktori"); } }
class B extends A { B() { System.out.println("B konstruktori"); } }
class C extends B { C() { System.out.println("C konstruktori"); } }

public class Main {
    public static void main(String[] args) {
        new C();
    }
}

First A konstruktori, then B konstruktori, and last C konstruktori. The first thing each constructor does is call super(), so the chain runs from the topmost parent downward.

📖 Answer

When new C() is called, control first enters C(), but its first (invisible) line is super(). That goes to B(), which immediately calls A(), which calls Object(). After that the bodies run on the way back down:

A konstruktori
B konstruktori
C konstruktori

This makes sense logically: a child class relies on the parent part, so the parent part has to be ready first.

The detailed order (within a single class):

  1. the parent constructor (super(...));
  2. field initializers and instance { } blocks, in the order they are written;
  3. the rest of the constructor body.

static blocks are separate: they run once, when the class is first loaded, again from parent to child. If the question also has static { } blocks, all the static blocks print first, then the constructors.