-1

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!

dog bytes
  • 23
  • 4
  • 2
    Hint: if a constructor doesn't explicitly delegate to another through `this(...)` or `super(...)`, it's equivalent to having `super()`. So imagine the parameterless constructor for `C` starts `super();` - would that clear up your confusion? – Jon Skeet Feb 27 '23 at 10:39
  • oh yeah, i forgot that super() is invoked even if not explicitly, thank you! – dog bytes Feb 27 '23 at 10:41

1 Answers1

1

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.

Miss Skooter
  • 803
  • 10
  • 22