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)?
Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The constructors of inherited classes are called in the same order in which they are inherited.
No, constructor cannot be inherited in java. If parent class constructor is inherited in child class, then it can not be treated as constructor because constructor name must be same as of class name.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With