Constructor chaining refers to the ability to call a constructor from within another constructor. You can use a constructor chain either within the same class or even with a different one. For the latter, the constructor should be done by inheritance from the super class.
In this Java programming tutorial, you will learn about the three ways in which you can perform constructor chaining.
Java constructor chaining in the same class
You can create multiple constructors in the same class, each with a different number of accepted arguments. To call one of the constructors in another constructor (of the same class), use the this () keyword.
If the constructor you are calling accepts some arguments, enclose them in the parentheses of this (). It is important to note that when calling a constructor, this () should always be the first statement in the calling constructor.
There must also be at least one constructor that does not use the this () statement.
Consider the following Java example that shows how constructors are concatenated in the same class:
public class ChainWithinClass {ChainWithinClass () {System.out.println (” nThis is the constructor with no arguments.”); } ChainWithinClass (int y) {this (); int var1 = y; System.out.println (“You passed an 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 produces the following output:
This is the constructor with no arguments. You passed an 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 in this example is how the constructors are called. It explains the order in which the messages appear on your screen.
If arguments 2 and 4 are passed to ChainWithinClass () during instantiation, the first thing that is called is the ChainWithinClass (int a, int b) constructor.
This (3) then calls the ChainWithinClass (int y) constructor within this constructor. Within the body of ChainWithinClass (int y), the statement that calls the constructor without arguments is executed first.
If the constructor is called with no arguments, the message “This is the constructor with no arguments” is displayed. is then printed out. Then the rest of the instructions in ChainWithinClass (int y) are executed and finally those of ChainWithinClass (int a, int b).
Before proceeding to the next section, note that the order in which the constructors appear in the body of the class does not affect the order in which they are executed.
Read: String objects in Java
Constructor chaining to another class in Java
As mentioned earlier, constructor chaining to another class is done by inheritance. The most important point here is that the constructors of the superclass are called before those of the subclass.
To call the constructors of the base class, simply use the super () statement in the constructor of the child class. As with constructor chaining within the same class, the super () statement should always be the first in your subclass constructor.
The following code is an example of chaining a constructor with 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 you entered is” + fname); System.out.println (“You are” + age + “years old.”); } Account () {System.out.println (” nWelcome dear customer”); } public static void main (String args[]) {FixedDeposit-Account = new FixedDeposit (); }} FixedDeposit class extends Account {FixedDeposit () {super (); // Calling the constructor without arguments in the base class double APY = 12.5; System.out.println (“Your current interest rate is” + APY + “%”); }}
Running this code produces 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.
Interestingly, even though the super () statement was not explicitly included, the subclass constructor would still have called the superclass constructor with no arguments.
However, this means that if your superclass doesn’t define a constructor with no arguments, regardless of whether you haven’t used super (), you will get a compiler error.
If you have a parameterized constructor, you can avoid this by calling it. In this example it is Account (String first_name, int your_age).
Simply pass the values through the round brackets in super ():
super (“Maurice”, 31);
Read: The best Java IDEs
Using an initialization block for constructor chaining in Java
In addition to using constructors to initialize values when instantiating a class, you can also use an initialization block. The syntax is simple and consists of just two curly brackets and the block of code they contain:
{// write your code here}
Initialization blocks are used when you want certain statements to be executed in all of the constructors you define. They are always executed first in the constructor before the other code in it.
An important point to note is that initialization blocks are executed in the order they appear in the body of the class.
class Apples {{System.out.println (” nThis is fresh from South Africa.”); } Apples () {System.out.println (“color: green”); } {System.out.println (“No artificial fertilizers used!”); } Apples (string color) {System.out.println (“color:” + color); } public static void main (String args[]) {Apples myApple = new apples (); }}
Here is the expected output when running this code:
This is fresh from South Africa. No artificial fertilizers used! color green
Read: Introduction to progressive web apps in Java
Summary of constructor chaining in Java
Constructor chaining gives you a utility similar to method overloading. It allows you to define multiple constructors and call them with the same initialization. Ultimately, constructor chaining simplifies the initialization of values.