Constructor Chaining in Java


Create a Java program to demonstrate constructor chaining

  • The Parent class has a constructor that prints "Parent Constructor" when invoked.
  • The Child class extends Parent, which means it inherits from Parent. It has its own constructor that prints "Child Constructor".
  • In the main method of the Child class, an instance of Child is created using new Child(). When this happens, first the constructor of the Parent class is invoked due to inheritance, and then the constructor of the Child class is invoked.

Source Code

class Parent
{
	Parent()
	{
		System.out.println("Parent Constructor");
	}
}
 
class Child extends Parent
{
	Child()
	{
		System.out.println("Child Constructor");
	}
 
	public static void main(String[] args)
	{
		Child child = new Child();
	}
}

Output

Parent Constructor
Child Constructor