javasequenceextendsextend

Questioning the order in which the code is executed


So I stumbled across this piece of code (Java - Constructor does not explicitly invoke a superclass constructor, Java does not insert one either)...

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

class A {
    public A(){
        this(5);
        System.out.println("a1");
    }

    public A(int x){
        System.out.println("a2");
    }
}

class B extends A {
    public B(){
        this(false);
        System.out.println("b1");
    }

    public B(int x){
        super();
        System.out.println("b2");
    }

    public B(boolean b){
        this(2);
        System.out.println("b3");
    }
}

class C extends B {
    public C(){
        System.out.println("c1");
    }

    public C(double x){
        this();
        System.out.println("c2");
    }
}

And the output that I got is a2 a1 b2 b3 b1 c1 a2 a1 b2 b3 b1 c1 c2

I was expecting it to be c1 c2 only but I just cannot wrap my head around the sequence in which the code is executed.

I would love a detailed explanation, just to make sure I understand things clearly enough. Thank you!


Solution

  • Inheriting classes call super() implicitely at the beginning of the constructor.

    Thus, the execution is as follows:

    C() --> B() --> A() --> A(5) --> print('a2') --> print('a1') --> B(false) --> B(2) --> print('b2') --> print('b3') --> print('b1') --> print('c1') (this finishes the very first call to C())

    C(1.0) --> does the exact same trajectory for a2, a1, b2, b3, b1, c1, and then finally print('c2') to finish the function.