Java – Constructor chaining with example

In this article, we will learn constructor chaining in detail

1. Constructor Chaining:

Calling one constructor from another constructor is known as constructor chaining in Java. There are 2 important keywords available to perform constructor chaining i.e.;

  • this() constructor call, is used to invoke constructor of same class whereas
  • super() constructor call, is used to invoke constructor of super class

1.1 Example on constructor chaining using this() constructor

  • To demonstrate the use of this() constructor
  • we will have a simple Java class with three overloaded constructors

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// member variables
	int employeeId;
	String employeeName;
	String employeeOrg;

	// default constructor
	Employee() {

		// an implicit super() constructor call to java.lang.Object is always present
		System.out.println("Employee class >> Inside default constructor");
		this.employeeOrg = "Google Corporation Inc.";
	}

	// parametrized constructor with 1 argument (String)
	Employee(String name) {

		this(); // to invoke another constructor from same class, this() constructor is used

		System.out.println("Employee class >> Inside parametrized constructor with 1 argument (String)");
		this.employeeId = 0; // think of a contractual employee
		this.employeeName = name;
	}

	// parametrized constructor with 2 arguments (int, String)
	Employee(int id, String name) {

		this(name); // to invoke another 1-argument overloaded constructor 
                         // from same class, this(String) constructor is used

		System.out.println("Employee class >> Inside parametrized constructor" 
                                    + " with 2 arguments (int, String)");
		this.employeeId = id;
	}

	// display() method
	void displayEmployeeInfo() {
		System.out.println("\nEmployee details:  \n\nOrgnaization: " + employeeOrg 
+ "\nId: " + employeeId + "\nName: " + employeeName + "\n");
	}

	// main() method - entry point to JVM
	public static void main(String args[]) {

		// construct an object for permanent employee
		System.out.println("Creating and displaying permanent employee details\n");
		Employee permanentEmp = new Employee(19, "Rahul Dravid");
		permanentEmp.displayEmployeeInfo();

		System.out.println("******************************************************************");

		// construct an object for contract employee
		System.out.println("Creating and displaying contract employee details\n");
		Employee contractEmp = new Employee("Jim Dawson");
		contractEmp.displayEmployeeInfo();

		System.out.println("******************************************************************");
	}
}

Output:

Creating and displaying permanent employee details

Employee class >> Inside default constructor
Employee class >> Inside parametrized constructor with 1 argument (String)
Employee class >> Inside parametrized constructor with 2 arguments (int, String)

Employee details:  

Orgnaization: Google Corporation Inc.
Id: 19
Name: Rahul Dravid

******************************************************************
Creating and displaying contract employee details

Employee class >> Inside default constructor
Employee class >> Inside parametrized constructor with 1 argument (String)

Employee details:  

Orgnaization: Google Corporation Inc.
Id: 0
Name: Jim Dawson

******************************************************************

Explanation:

In above Employee class,

  • There are 3 overloaded constructors with one being default constructor and other two is parametrized constructor
  • Whenever an object is created using 2-arguments constructor then call to this(String) invokes 1-argument constructor which should be 1st line of the constructor statement which again invoke default constructor
  • Similarly, when 1-argument constructor is used to create object then this() constructor call is used to invoke default constructor of the same class

Till now, we have seen constructor chaining example in same class using this() constructor. Let us move on and explore constructor chaining examples with inheritance concepts using super() constructor call

1.2 Example on constructor chaining using super() constructor

  • To demonstrate the use of super() constructor call
  • we will have two Java classes viz.; Employee and PermanentEmployee class
  • we will call super class Employee’s constructor from child class PermanentEmployee constructor via super() constructor call
  • Note: PermanentEmployee class inherits Employee class

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// member variables
	int employeeId;
	String employeeName;
	String employeeOrg;

	// default constructor
	Employee() {

		// an implicit super() constructor call to java.lang.Object is always 
// present until we specify explicitly
		System.out.println("Employee class >> Inside default constructor");
		this.employeeOrg = "Google Corporation Inc.";
	}

	// parametrized constructor with 1 argument (String)
	Employee(String name) {

		this(); // to invoke another constructor from same class, this() constructor is used

		System.out.println("Employee class >> Inside parametrized constructor with 1 argument (String)");
		this.employeeName = name;
	}
}

PermanentEmployee.java

package in.bench.resources.constructor.example;

public class PermanentEmployee extends Employee {

	// parametrized constructor with 2 arguments (int, String)
	PermanentEmployee(int id, String name) {

		super(name); // call to super class's constructor

		System.out.println("PermanentEmployee class >> Inside parametrized constructor "
                                                   +" with 2 arguments (int, String)");
		this.employeeId = id;
	}

	// display() method
	void displayEmployeeInfo() {
		System.out.println("\nEmployee details:  \n\nOrgnaization: " + employeeOrg 
+ "\nId: " + employeeId + "\nName: " + employeeName + "\n");
	}

	// main() method - entry point to JVM
	public static void main(String args[]) {

		// construct an object for permanent employee
		System.out.println("Creating and displaying permanent employee details\n");

		PermanentEmployee permanentEmp = new PermanentEmployee(19, "Rahul Dravid");
		permanentEmp.displayEmployeeInfo();

		System.out.println("******************************************************************");
	}
}

Output:

Creating and displaying permanent employee details

Employee class >> Inside default constructor
Employee class >> Inside parametrized constructor with 1 argument (String)
PermanentEmployee class >> Inside parametrized constructor with 2 arguments (int, String)

Employee details:  

Orgnaization: Google Corporation Inc.
Id: 19
Name: Rahul Dravid

******************************************************************

Explanation:

In above example,

  • Child class PermanentEmployee have one 2-arguments parametrized constructor which invokes parent class’s 1-argument constructor using super() constructor call and this must 1st line of the constructor statement
  • Parent class Employee have 2 constructors viz.; default no-arg constructor and 1-argument constructor
  • Invocation from child class will first hit 1-argument constructor in parent class which initializes instance variable employee name, but before that
  • this() constructor call will hit default constructor where organization name gets initialized
  • Finally, after all instance variables initialization are done through constructor chaining process –> display() method is invoked using newly created object
  • display() method prints all details pertaining to particular employee

2. Point to remember about constructor & constructor chaining in Java:

  • An implicit call to super class’s constructor is always present in any constructor and it is first line of the constructor statement (i.e.; super();)
  • Until and unless, we explicitly declare a this() constructor or super() constructor call
  • If declared explicitly i.e.; this() or super(), then it must be 1st statement of the constructor
  • But both cannot be present simultaneously at a given time
  • this() constructor call is used to invoke one of the overloaded constructor in same class
  • whereas super() constructor call is used to invoke super class’s constructor through inheritance
  • this() is referred to call default constructor and this(5); is used to invoke overloaded constructor with one argument of data type int
  • Similarly, super() constructor call invokes super class’s default constructor and super(“BenchResources”); is used to invoke super class’s constructor with one arguments of String data type

Q) But what is the real purpose of constructor chaining?

From last example for constructor chaining using super() constructor call,

  • Organization name of every employee belonging one company going to remain same, so there is no need initialize it again and again
  • Therefore, we have moved more general and common attribute “organization name” to super class constructor
  • And in child class constructor, we have kept specific attributes like employee id and name
  • To add or store a new employee record, we have pass just id & name and organization name is get initialized through constructor chaining process

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Method v/s Constructor
Java - Constructor overloading with example