Java constructor inheritance?

constructor, inheritance, java

Solution

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

Problem

I always thought that constructors aren't inherited, but look at this code: ``` class Parent { Parent() { System.out.println("S1"); } } class Child extends Parent { Child() { System.out.println("S2"); } } public class Test5 { public static void main(String[] args) { Child child = new Child(); } } //RESULT: //S1 //S2 ``` It shows that Child inherited constructor. Why there is S1 on result? Is there any possibility to create 2 constructors without parameters and have only Child constructor on result without base constructor (only S2)?

Original source