Java Constructor Inheritance
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
Java doc says :
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
If you don't declare a constructor of any type, a default is added.
If you don't call any other constructor in the first line of your subclass, a call to super() is made.
You write:
It shows that Child inherited constructor.
Constructors can not be inherited. Classes can be inherited, so Child does not inherit any constructor. Child inherits class Parent. Parent inherits class Object. When you call the Child constructor, automatically an Object constructor is called and then a Parent constructor, before the code of the Child constructor is run.
This why you get this result:
S1
S2