0

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");
    }
}
2
  • Which part of the output were you not expecting? Commented Aug 16, 2014 at 12:50
  • I had expected it to start of with [a2 a1 a2 a1 a2 a1..] because of I thougt the compiler would add super() in the first and third constructor of class B. What @Mureinik says makes sense, thank you! Commented Aug 16, 2014 at 13:08

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 And if it didn't work this way, super() would be invoked twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.