top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Constructor Chaining In Java

Introduction

Java is an object-oriented program that thrives on robust constructs. A key concept in this universe is 'Constructor chaining in Java.' It's an elegant technique that you should consider grasping as a software developer. It makes your code cleaner, more efficient, and easier to understand. In constructor chaining, you call one constructor from another within the same class.

Overview

Our exploration of "Constructor Chaining in Java" will unfold across several vital sections. Each is designed to improve your understanding of the subject matter incrementally.

We'll start with the basics, introducing the concept of constructor chaining and its implications in Java. To make the learning process engaging and hands-on, we will walk you through practical examples. This step-by-step approach will ensure you understand constructor chaining in Java with examples.

Next, we'll take you through a particular type of chaining known as “Constructor chaining in Java using super.” This approach will allow you to explore how superclass constructors can be invoked in subclass constructors.

Moving ahead, we'll categorize and explain the 'Types of constructor chaining in Java'. Differentiating between them will provide you with the flexibility to choose the most appropriate type depending on the coding requirements.

We'll then compare local chaining and constructor chaining in Java, highlighting the unique characteristics and applications of each. This understanding will equip you with the knowledge to make more informed coding decisions.

By the end of this guide, you will have a thorough understanding of constructor chaining in Java, supported by hands-on examples and practical knowledge. Your journey through this material will enhance your Java programming skills and open new avenues for more efficient coding practices.

What Is Constructor Chaining in Java?

Constructor chaining in Java is the process of calling one constructor from another with respect to the current object. This technique allows you to ensure that a series of constructors, each with a different parameter list, are executed in a specific order.

This is a powerful concept because it allows you to set up a Java object in a consistent and controlled manner, no matter which constructor is called. It can make your code cleaner, more readable, and easier to maintain.

Constructor Chaining in Java with Example


In this code, the ChainingDemo class has two constructors. When an object of ChainingDemo is created using the default constructor, it automatically calls the single parameter constructor using the this() keyword. The this(10) statement chains the constructors together, ensuring the single parameter constructor is called before the default constructor. The result is that the val variable is initialized to 10.

Here's the output:


The Need for Constructor Chaining

Constructor chaining is a key concept in Java that offers  numerous benefits, and understanding these needs will help you appreciate its importance in code design and implementation.

  1. Code Reusability: A core benefit of constructor chaining is that it promotes code reusability. Instead of writing the same code in multiple constructors, you can write it once and call that constructor from other constructors.

  2. Consistency: Constructor chaining can ensure that an object is always in a valid state before it's used. This makes the code more robust and reliable.

  3. Controlled Initialization: It allows controlled initialization of objects. This is useful when we want certain codes to always run whenever an object is created.

Let's consider the following constructor chaining in Java example

In this code, we have an Employee class with three fields (name, age, department). There are three constructors, each handling a different scenario:

  • The default constructor creates an Employee with the name, age, and department set to "Unassigned" and 0.

  • The second constructor creates an Employee with a given name and age, but the department is set to "Unassigned".

  • The third constructor creates an Employee with a given name, age, and department.

Output

Rules of Constructor Chaining

There are certain rules that govern the process of constructor chaining in Java. Understanding these rules will let you apply this concept effectively and correctly. Here are the key rules:

  1. Constructor call must be the first statement: In Java, a call to another constructor (using this()) or a call to a superclass constructor (using super()) must be the first statement in the constructor.

  2. Recursion not permitted: Recursive constructor invocation is not allowed. In simpler terms, a constructor cannot directly or indirectly call itself, as this would lead to an infinite loop and eventually a StackOverflowError.

  3. Only one call is allowed: A constructor can call at most one other constructor. It can either call another constructor in the same class (with this()) or it can call a constructor in the superclass (with super()), but it cannot do both.

Let's illustrate these rules with an example:


This program demonstrates Rules 1 and 3. The this(10); statement, which is a call to another constructor, is the first statement in the default constructor, following Rule 1. It also shows Rule 3, because only one other constructor is called.

Output

However, if we modify the Test(int value) constructor to call this(), it will result in a recursive constructor invocation, violating Rule 2 and leading to a StackOverflowError:

Ways to Implement Java Constructor Chaining

There are two types of constructor chaining in Java:

  1. Constructor chaining within the same class

  2. Constructor chaining from a parent (or base) class

Constructor Chaining Within the Same Class

When constructor chaining is used within the same class, it involves calling one constructor from another constructor in the same class. The keyword this() is used to call another constructor in the same class.

Here's an example:


In this example, when an object of the Demo class is created using the default constructor, it automatically calls the parameterized constructor, initializing the value to 10.

Output


Constructor Chaining from Parent/Base Class

In Java, a subclass constructor can call a constructor in its superclass. The keyword super() is used to call a constructor in the parent class.

Here's an example:

In this example, when an object of the Child class is created, it automatically calls the constructor of its parent class Parent, followed by the constructor in the Child class itself.

Output


Constructor Calling From Another Constructor

In Java, you can call one constructor from another constructor within the same class. This process is known as constructor chaining, and the keyword this() is used to make this call. It's a useful technique to maintain cleaner code and promote code reusability.

An example of a Constructor Calling From Another Constructor:

In this code, when we create a Vehicle object using the default constructor, it automatically calls the parameterized constructor due to the this("Car", 0); statement. This initializes type as "Car" and speed as 0. The call to the parameterized constructor must be the first statement in the calling constructor.

Output


This shows that the parameterized constructor is called first, followed by the default constructor. The Vehicle object's type and speed values are displayed as initialized by the parameterized constructor.

Calling Super Class Constructor

In Java, a subclass constructor has the ability to call a constructor from its superclass. This is a form of constructor chaining in Java using super. This mechanism allows a subclass to inherit the fields and methods of its superclass, ensuring that the superclass constructor's initialization code is executed before the subclass constructor's code. The keyword super() is used for this purpose.

For example:


In this example, when an object of the Dog class is created, it first calls the constructor of its superclass Animal because of the super(); statement. This initializes the type field. Then the Dog constructor is executed, initializing the name field.

Output


This shows that the superclass constructor is called first, followed by the subclass constructor. The type and name values are displayed as initialized by the Animal and Dog constructors respectively.

What If We Change the Order of Constructors?

In Java, the order in which constructors are declared in the class does not affect how they are called or their execution. The constructor called depends on the arguments passed when creating an object of the class.

However, within a constructor, the call to another constructor using this() or to a superclass constructor using super() must be the first statement. If it's not, you will receive a compilation error.

For example:


Here, even though the parameterized constructor (Constructor 1) is declared before the default constructor (Constructor 2), when we create an object with the default constructor, it first calls the parameterized constructor due to the this(10); statement. After that, it continues executing the rest of the default constructor.

Output


An Alternative Method of Constructor Chaining Using the Init Block

Besides constructor chaining in Java, there's another method to initialize common logic across constructors, which is known as the initialization block, or 'init block' for short. The init block is a block of code that looks like a method, but it's outside any method and is written directly within the class. It is executed whenever an instance of the class is created, no matter which constructor is called.

Here's an example to show how the init block works:

In this code, the init block is called every time an object of the Demo class is created. It initializes the value to 10. Then, depending on the constructor used to create the object, the value may be reinitialized. If the default constructor is used, the value remains 10. If the parameterized constructor is used, the value is changed to the parameter value.

Output

This shows that the init block is called before each constructor, performing common initialization logic.

The Differences Between Local Chaining And Constructor Chaining In Java


Local Chaining

Constructor Chaining

What

Method chaining in a single statement.

One constructor calls another.

Use

Invoking methods that return the object instance.

Performing common actions in multiple constructors.

How

Using return this;

Using this() within a class, super() from a subclass.

Scope

Limited to a particular method call.

Applies to an entire class or between a class and its superclass.

Conclusion

Constructor chaining in Java is a powerful feature that allows one constructor to call another constructor within the same class or in its superclass. This process ensures efficient initialization of objects, eliminates code redundancy, and enhances the readability of the code. Constructor chaining within the same class is achieved using the this() keyword, while chaining from a subclass to a superclass is done using super(). Other concepts, like the initialization block and local chaining, offer additional techniques for code reuse and organization. Mastering these concepts can contribute to writing cleaner, more efficient Java code.

FAQs

1. What happens when the this() or super() keywords are not included in a constructor?

If this() or super() are not included explicitly, Java implicitly includes them. For a subclass constructor, if super() is not included, Java will automatically insert a no-argument super() as the first statement, thus calling the superclass's no-argument constructor. For this(), if not used, it simply means there's no explicit call to another constructor in the same class.

2. What are the limitations of using constructor chaining in Java?

The main limitation is that a constructor call, whether this() or super(), must be the first statement in a constructor. Additionally, you can't use both this() and super() in the same constructor, as both have to be the first statement.

3. How is constructor chaining different from method overloading?

Constructor chaining is a process where one constructor calls another within the same class or a superclass. Whereas method overloading is a feature that allows a class to have two or more methods with the same name but different parameters.

4. How does constructor chaining relate to the concept of inheritance in Java?

Constructor chaining is closely linked to inheritance. When creating an instance of a subclass, the constructor of its superclass is always invoked first to ensure proper initialization of the fields inherited from the superclass. This is achieved via constructor chaining with the super() keyword.

Leave a Reply

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