JavaA Guide to Constructor Chaining in Java

A Guide to Constructor Chaining in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java Developer Tutorials

Constructor chaining refers to the ability to call a constructor inside another constructor. You can use a constructor chain either within the same class or even with another one. For the latter, the constructor should be through inheritance from the super class.

In this Java programming tutorial, you will learn the three ways in which you can carry out constructor chaining.

Java Constructor Chaining in the Same Class

You can create multiple constructors in the same class, each with a different number of arguments that it accepts. To call one of the constructors in another constructor (of the same class), use the keyword this().

If the constructor you are calling takes some arguments, then include them in the round brackets of this(). It is important for you to note that when using this() to call a constructor, it should always be the first statement in the calling constructor.

There also needs to be at least one constructor that does not use the statement this().

Consider the Java example below showing how to chain constructors in the same class:

public class ChainWithinClass
{
   ChainWithinClass(){
       System.out.println("\nThis is the no-arg constructor.");
   }
 
   ChainWithinClass(int y){
       this();
       int var1 = y;
       System.out.println("You passed one argument: " + var1);
   }
 
   ChainWithinClass(int a, int b){
       this(3);
       int var2 = a;
       int var3 = b;
       System.out.println("You passed two arguments: " + var2 + " and " + var3);
   }
 
   public static void main(String[] args){
       ChainWithinClass chainObj = new ChainWithinClass(2,4);
   }
}

Running this code will produce the following output:

This is the no-arg constructor.
You passed one argument: 3
You passed two arguments: 2 and 4

The example shows how you can use three different constructors in the same class: one with no argument, one with only one argument, and the third with two arguments.

A very interesting point to consider in this example is how the constructors are called. It explains the order in which the messages are output on your screen.

When the arguments 2 and 4 are passed to ChainWithinClass() at instantiation, the constructor ChainWithinClass(int a, int b) is the first to be called.

Inside this constructor, the constructor ChainWithinClass(int y) is then called by this(3). Inside the body of ChainWithinClass(int y), the statement calling the no-arg constructor is the first to be run.

When the no-arg constructor is called, the message “This is the no-arg constructor.” is then printed out. After this, the remaining statements in ChainWithinClass(int y) are executed and then finally those of ChainWithinClass(int a, int b).

Before moving into the next section, note that the order in which the constructors appear in the class’ body does not influence the order in which they are run.

Read: Strings Objects in Java

Constructor Chaining to Another Class in Java

As mentioned earlier, constructor chaining to another class happens through inheritance. The key point to note here is that the constructors in the super class are called before those of the sub class.

To call the constructors in the base class, simply use the statement super() in the constructor of the child class. Just like constructor chaining within the same class, the statement super() should always be the first one in the constructor of your subclass.

See the code below for an example of how to chain a constructor to another class in Java:

class Account{
  
   Account(String first_name, int your_age){
       String fname = first_name;
       int age = your_age;
 
       System.out.println("\nThe name entered is " + fname);
       System.out.println("Your are " + age + " years old.");
   }
 
   Account(){
       System.out.println("\nWelcome dear customer");
   }
 
   public static void main(String args[]){
       FixedDeposit acct = new FixedDeposit();
   }
 
}
 
class FixedDeposit extends Account{
 
   FixedDeposit(){
 
       super(); // calling the no-arg constructor in the base class
       double APY = 12.5;
       System.out.println("Your current interest rate is " + APY + "%");
   }
}

Running this code will produce the following output:

Welcome dear customer
Your current interest rate is 12.5%

The above code shows how a subclass FixedDeposit calls the constructor in the superclass Account.

An interesting thing to note is that even though the statement super() was not explicitly included, the subclass constructor would have still invoked the super class’ no-arg constructor.

That said, this means that you will get a compiler error if your superclass doesn’t define a no-arg constructor, regardless of whether you did not use super().

If you have a parameterized constructor, you can avoid this by calling it. For this example, that is Account (String first_name, int your_age).

Simply pass the values through the round brackets in super():

super("Maurice",31);

Read: The Top Java IDEs

Using an Initialization Block for Constructor Chaining in Java

Apart from using constructors to initialize values when a class is instantiated, you can also use an initialization block. The syntax is simple and merely consists of two curly brackets and the block of code in it:

{
// write your code here 
}

Initialization blocks are used when you want certain statements to be executed in all the constructors you define. They are always the first to be executed in the constructor before the other code in it.

A key point to note is that initialization blocks are run in the order in which they appear in the class’ body.

class Apples{
 
   {
       System.out.println("\nThis is fresh from South Africa.");
   }
 
   Apples(){
       System.out.println("Color: Green");
   }
 
   {
       System.out.println("No artificial fertilisers used!");
   }
 
   Apples(String color){
       System.out.println("Color: "+ color);  
   }
 
public static void main(String args[]){
   Apples myApple = new Apples();
}
}

Here is the expected output from running this code:

This is fresh from South Africa.
No artificial fertilisers used!
Color: Green

Read: Introduction to Progressive Web Apps in Java

Summary of Constructor Chaining in Java

Constructor chaining provides you a similar utility to that provided by method overloading. It enables you to define multiple constructors and be able to call them using the same initialization. Constructor chaining ultimately simplifies how you initialize values.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories