Search code examples
javacontrol-flow-graph

Super constructor call order


In the following example which constructor of the class U calls invokes the super constructor? The one without arguments or the one with one argument ?

public class T{
    T(){
        System.out.println("T()");
    }
       public static void main(String[] args){
        new U();
    }
}

class U extends T{
    U(){
        this(2);
        System.out.println("U()");
    }
    
    U(int x){
        System.out.println("U(int x)");
    }
}

Solution

  • The first constructor U() calls the second constructor U(int x) via the this(2) call.

    The second constructor U(int x) calls the super class constructor T() implicitly.

    Which means both U constructors call the super class constructor, either directly or indirectly.