Search code examples
javaclassinheritanceconstructorsuperclass

Java - Constructor does not explicitly invoke a superclass constructor, Java does not insert one either


First, this is what I read on docs.oracle.com

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

But when I test my code, the no argument constructor of class B does not have a superclass constructor AND Java doesn't add one. Why is this? This is what I had expected:

   public B(){
        super(); //<--- Why didn't Java add this superclass constructor? 
        this(false);
        System.out.println("b1");
    }

Does it has something to do with the fact that the "public B()" constructor calls another constructor which calls another one which DOES have a superclass constructor?

The output I get is: a2 a1 b2 b3 b1 c1 a2 a1 b2 b3 b1 c1 c2

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

Class A

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

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

Class B

public 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

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

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

Solution

  • A call to this(args) is evaluated before anything else. So B() calls B(boolean), which calls B(int), which explicitly calls super().