Why do we have a way out: S1S2 in this case?

In the code below, the output is: S1S2. Why are we getting results?

 public class S1 {
     public static void main(String[] args) {
         new S2();
     }
     S1(){
         System.out.print("S1");
     }
 }
 class S2 extends S1{
     S2(){
         System.out.print("S2");
     }
 }

      

+3


source to share


3 answers


Since S2 extends S1, it is equivalent to calling all constructors in top-to-bottom order.



Java will first create the parent S1 object and call its constructor. Then go to the next object, S2 with its constructor.

+3


source


If a derived class constructor does not explicitly call its base class constructor (via super(...)

), then there is an implicit call

super();

      



to the default constructor of the base class in every constructor of the derived class.

+2


source


There is an implicit call to the default constructor of the superclass in the constructor of the subclass.

Here's a quote from Spec:

If the constructor body does not begin with an explicit constructor invocation and the declared constructor is not part of the original class object, then the constructor body is implicitly assumed by the compiler to begin with the superclass constructor invocation "super ();", the constructor invocation of its direct superclass, which takes no arguments.

+2


source







All Articles