Constructors in Inheritance
In Java, when a class inherits another class, the constructor of the parent class is executed first, followed by the constructor of the child class. This ensures that the base class is properly initialized before the derived class adds its own functionality.
How Constructors Work in Inheritance#
When an object of a derived class is created, the constructor of the base class is automatically called first. If there is no explicit call to the superclass constructor, Java automatically invokes the default constructor of the superclass.
Example 1: Default Constructor in Inheritance#
Output:
Explanation:#
- When we create an object of
Child
, the constructor ofParent
is called first. - After that, the constructor of
Child
is executed.
Using super()
to Call Parameterized Constructor#
By default, the Java compiler automatically calls the parent class’s default constructor. However, if the parent class does not have a default constructor, we must explicitly call a parameterized constructor using super()
.
Example 2: Using super()
to Call Parameterized Constructor#
Output:
Explanation:#
- The
super(name)
call explicitly invokes the constructor of the parent class. - This ensures that the parent class is initialized properly before executing the child class constructor.
Constructor Chaining in Inheritance#
Constructor chaining refers to the process where one constructor calls another constructor in the same or parent class using this()
or super()
.
Example 3: Constructor Chaining#
Output:
Explanation:#
- The
super()
calls ensure that constructors are called from the base class to the derived class in the correct order.
Conclusion#
In this blog, we learned how constructors behave in Java inheritance. We explored how superclass constructors are called before subclass constructors, how to use super()
to call parameterized constructors, and the concept of constructor chaining. Understanding these concepts helps in building efficient object-oriented Java applications.