Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor chaining in Java, when is super called?

If you have a constructor which calls this() when is super() called? In the first constructor called? Or in the last constructor without the keyword this()?

Main calls: new B()

public class A {
    public A(){
       System.out.print("A ");
    }
}
public class B extends A {
 public B(){
       // is super called here? Option 1
       this(1);
       System.out.print("B0 ");
    }
 public B(int i){
       // or is super called here? Option 2
       System.out.print("B1 ");
    }
}

In this example the Output is: "A B1 B0". But it isn't clear to me, if the super() constructor is called at Option 1 or Option 2 (because the Output would be the same, in this case).

like image 738
Avery Avatar asked Feb 06 '26 06:02

Avery


1 Answers

You can deduce the answer by following this simple rule:

Only one super constructor will be called, and it will only be called once.

So, the super constructor could not possibly be invoked from B() because it would be invoked again from B(int).

Specifically, in the Java Language Specification (JLS) section 8.8.7. "Constructor Body" we read:

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

In other words, if the constructor body does begin with an explicit constructor invocation, then there will be no implicit superclass constructor invocation.

(When the JLS speaks of a constructor body beginning with "an explicit constructor invocation" it means an invocation of another constructor of the same class.)

like image 104
Mike Nakis Avatar answered Feb 08 '26 20:02

Mike Nakis