Last Updated: 1 August, 2023
Constructor chaining refers to the process of calling one constructor from another constructor in Java by using the this() or super() keywords.
Uses of the this() and super() keywords in constructor chaining:
Let's see an example of constructor chaining using the this() keyword.
Example 1: Constructor Chaining with this() keyword
Output
Constructor with three parameters called...
Constructor with two parameters called...
Constructor with one parameter called...
Default constructor called...
Employee Name: Kavish
Employee ID: 195
Employee Designation: Manager
Let's see an example of constructor chaining using the super() keyword.
Example 2: Constructor Chaining with super() keyword
Output
Parent class - Default constructor called
Child class - Default constructor
Parent class - Default constructor called
Child class - Parameterized constructor value: Test
Parent class - Parameterized constructor value: My Test Data
Child class - two Parameterized (int, int) constructor value: 10 20
Example 3: Constructor Chaining with this() and super() methods
Output
Parent class - Parameterized constructor, Values :10 20
Parent class - Default constructor called.
Child class - Parameterized constructor, Values: Java Python
Child class - Default constructor called
Example 4: Order of Constructors execution in Inheritance
Output
A - default constructor
B - default constructor
C - default constructor
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com