Constructor Chaining In Java with Examples

In Java, constructor chaining is a sequence of invoking constructors upon initialising an object. It is used when we want to invoke a number of constructors, one after another by using only an instance. In this section, we will discuss constructor chaining in Java in detail with proper examples. Let’s have a quick look at what is a constructor in Java.


Constructor Chaining In Java 1

Constructor chaining is the process of calling one constructor from another constructor with respect to current object.
Constructor chaining can be done in two ways:

  • Within same class: It can be done using this() keyword for constructors in same class
  • From base class: by using super() keyword to call constructor from the base class.

Constructor chaining occurs through inheritance. A sub class constructor’s task is to call super class’s constructor first. This ensures that creation of sub class’s object starts with the initialization of the data members of the super class. There could be any numbers of classes in inheritance chain. Every constructor calls up the chain till class at the top is reached.

Suppose, there are five tasks to perform. There are two ways to perform these tasks, either implement all the tasks in a single constructor or create separate tasks in a single constructor.

By using the constructor chaining mechanism, we can implement multiple tasks in a single constructor. So, whenever we face such types of problems, we should use constructor chaining. We can make the program more readable and understandable by using constructor chaining.


Why do we need constructor chaining ?

This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable.
Constructor Chaining In Java 2

Rules of Constructor Chaining

  • An expression that uses this keyword must be the first line of the constructor.
  • Order does not matter in constructor chaining.
  • There must exist at least one constructor that does not use this

Constructor Calling form another Constructor

The calling of the constructor can be done in two ways:

  • By using this() keyword: It is used when we want to call the current class constructor within the same class.
  • By using super() keyword: It is used when we want to call the superclass constructor from the base class.

Note: In the same constructor block, we cannot use this() and super() simultaneously.


Constructor Chaining Examples

Calling Current Class Constructor

We use this() keyword if we want to call the current class constructor within the same class. The use of this() is mandatory because JVM never put it automatically like the super() keyword. Note that this() must be the first line of the constructor. There must exist at least one constructor without this() keyword.

Syntax: this(); or this(parameters list);  

For example:

this();   
this(“Javatpoint”);  

Let’s create a Java program and call the current class constructor.

ConstructorChain.java


public class ConstructorChain  
{  
//default constructor  
ConstructorChain()  
{  
this("Javatpoint");  
System.out.println("Default constructor called.");  
}  
//parameterized constructor  
ConstructorChain(String str)  
{  
System.out.println("Parameterized constructor called");  
}  
//main method  
public static void main(String args[])   
{   
//initializes the instance of example class  
ConstructorChain cc = new ConstructorChain();   
}   
}  

output: 
Parameterized constructor called 
Default constructor called
In the above example, we have created an instance of the class without passing any parameter. It first calls the default constructor and the default constructor redirects the call to the parameterized one because of this(). The statements inside the parameterized constructor are executed and return back to the default constructor. After that, the rest of the statements in the default constructor is executed and the object is successfully initialized. The following is the calling sequence of the constructor:
ConstructorChain cc = new ConstructorChain(); -> ConstructorChain() -> ConstructorChain(String str) -> System.out.println() -> ConstructorChain() -> System.out.println()  

Calling Super Class Constructor

Sometimes, we need to call the superclass (parent class) constructor from the child class (derived class) in such cases, we use the super() keyword in the derived class constructor. It is optional to write super() because JVM automatically puts it. It should always write in the first line. We get a syntax error if we try to call a superclass constructor in the child class.
Syntax: super(); or super(Parameter List);  
super(): It calls the no-argument or default constructor of the superclass.
super(parameters): It invokes the superclass parameterized constructor.
Remember that the superclass constructor cannot be inherited in the subclass. It can be called from the subclass constructor by using the super keyword.
Let’s create a Java program and implement constructor chaining in an inherited class.
ConstructorChaining.java



//parent class or base class  
class Demo  
{  
//base class default constructor  
Demo()  
{  
this(80, 90);  
System.out.println("Base class default constructor called");  
}  
//base class parameterized constructor  
Demo(int x, int y)  
{  
System.out.println("Base class parameterized constructor called");  
}  
}  
//derived class or child class  
class Prototype extends Demo  
{  
//derived class default constructor  
Prototype()  
{  
this("Java", "Python");  
System.out.println("Derived class default constructor called");  
}  
//derived class parameterized constructor  
Prototype(String str1, String str2)  
{  
super();  
System.out.println("Derived class parameterized constructor called");  
}  
}  
public class ConstructorChaining  
{  
//main method  
public static void main(String args[])   
{   
//initializes the instance of example class  
Prototype my_example = new Prototype();  
}   
}  

output : 
Base class parameterized constructor called
Base class default constructor called
Derived class parameterized constructor called
Derived class default constructor called

Constructor

In constructor chain, a constructor is called from another constructor in the same class this process is known as constructor chaining. It occurs through inheritance. When we create an instance of a derived class, all the constructors of the inherited class (base class) are first invoked, after that the constructor of the calling class (derived class) is invoked.

We can achieve constructor chaining in two ways:

  • Within the same class: If the constructors belong to the same class, we use this
  • From the base class: If the constructor belongs to different classes (parent and child classes), we use the super keyword to call the constructor from the base class.

Remember that changing the order of the constructor does not affect the output.


useful links for java : click here
if you want to learn about java then click here

Leave a Comment

Your email address will not be published. Required fields are marked *