DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Using Java Class Extension Library for Data-Oriented Programming
  • Test Parameterization With JUnit 5.7: A Deep Dive Into @EnumSource
  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL
  • JSON Handling With GSON in Java With OOP Essence

Trending

  • How to Prevent Data Loss in C#
  • Why Your QA Engineer Should Be the Most Stubborn Person on the Team
  • How to Build and Optimize AI Models for Real-World Applications
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  1. DZone
  2. Coding
  3. Java
  4. A Guide to Constructor Chaining in Java

A Guide to Constructor Chaining in Java

Constructor chaining in Java simplifies initialization and improves reusability by allowing one constructor to call another within a class or through inheritance.

By 
DZone Editorial user avatar
DZone Editorial
·
Feb. 13, 25 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
7.3K Views

Join the DZone community and get the full member experience.

Join For Free

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 must be inherited from the superclass. In this Java programming tutorial, you will learn the three ways to implement 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 constructor within another (of the same class), use this().

If the constructor you are calling takes arguments, then include them in the round brackets of this(). Note that when you use this() to call a constructor, it should always be the first statement in the calling constructor.

There must also be at least one constructor that does not use this().

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

Java
 
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:

Shell
 
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 arguments, one with a single argument, and the third with two arguments.

A very interesting point to consider in this example is the order in which constructors are called, which determines how messages are displayed on the 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.

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 superclass constructors execute before those of the subclass.

To call the constructors in the base class, simply use super() in the constructor of the child class. Just like constructor chaining within the same class, 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:

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 age " + 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:

Shell
 
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 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():

Java
 
super("Maurice",31);


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. Its syntax consists two curly brackets enclosing a block of code.

Java
 
{
// write your code here 
}


Initialization blocks ensure certain statements execute in all defined constructors. They always run first before the constructor executes any other code.

A key point to note is that initialization blocks execute in the order they appear within the class’ body.

Java
 
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:

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


Summary of Constructor Chaining in Java

Constructor chaining offers similar benefits to method overloading. It enables you to define multiple constructors and call them with a shared initialization process. Constructor chaining ultimately simplifies object initialization.

Inheritance (object-oriented programming) Java (programming language) Object-oriented programming

Opinions expressed by DZone contributors are their own.

Related

  • Using Java Class Extension Library for Data-Oriented Programming
  • Test Parameterization With JUnit 5.7: A Deep Dive Into @EnumSource
  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL
  • JSON Handling With GSON in Java With OOP Essence

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook