Whatever you are seeing here is called as constructor chaining. Now What is Constructor Chaining:
Constructor chaining occurs through the use of inheritance. A subclass
constructor method's first task is to call its superclass' constructor
method. This ensures that the creation of the subclass object starts
with the initialization of the classes above it in the inheritance
chain.
There could be any number of classes in an inheritance chain. Every
constructor method will call up the chain until the class at the top
has been reached and initialized. Then each subsequent class below is
initialized as the chain winds back down to the original subclass.
This process is called constructor chaining.(Source)
That's what happening in your program. When you compile your program , your Child
is compiled to this way by javac
:
class Child extends Parent
{
Child()
{
super();//automatically inserted here in .class file of Child
System.out.println("S2");
}
}
And your Parent class is converted to following:
Parent()
{
super();//Constructor of Object class
System.out.println("S1");
}
That's why your output is showing as:
S1 //output from constructor of super class Parent
S2 //output from constructor of child Class Child