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.
Join the DZone community and get the full member experience.
Join For FreeConstructor 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:
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 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:
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:
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()
:
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.
{
// 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.
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
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.
Opinions expressed by DZone contributors are their own.
Comments