TeachingBee

How To Use Constructor Chaining in Java

Constructor chaining in java

Constructors can be used to initialise object upon creation. Constructors can be invoked during the creation of objects, typically using the new keyword. Constructors have a similar syntax to methods, however they do not have any return type and are given the same name of the class.

// Constructors In Java

public class TeachingBee {
// Default construtor
  TeachingBee() {
  }
}

There are two types of constructor in Java:

  • Default Constructor
  • Parameterised Constructor

In this article we will talk about constructor chaining in java using examples and what are the rules for constructor chaining in java and how does it work. So, let’s get started.

What Is Constructor Chaining In Java

The process of calling one constructor from another constructor with respect to current object is called constructor chaining in java. The constructors can belong to same class or can be of different class. For either of them we use different keywords to chain constructors which we will discuss further.

For Example:

// Constructor Chaining in Java

class TeachingBee {
  // Default Constructor
  public TeachingBee() {
    System.out.println("In Default Constructor Of TeachingBee Class");
  }
  // Parameterised Constructor
  public TeachingBee(String studentName) {
    System.out.println("In Parameterised Constructor Of TeachingBee Class: " + studentName);
  }
}

public class TeachingBeeStudent extends TeachingBee {
  // Default Constructor
  public TeachingBeeStudent() {

  // Constructor Chaining
    this("TeachingBeeStudent");
    System.out.println("In Default Constructor Of TeachingBeeStudent Class");
  }
  // Parameterised Constructor
  public TeachingBeeStudent(String studentName) {

 // Constructor Chaining
    super();
    System.out.println("In Parameterised Constructor Of TeachingBeeStudent Class: " + studentName);
  }

  public static void main(String args[]) {
    // Creating object of TeachingBeeStudent class
    TeachingBeeStudent studentObj = new TeachingBeeStudent();
  }
}

Output:

In Default Constructor Of TeachingBee Class
In Parameterised Constructor Of TeachingBeeStudent Class: TeachingBeeStudent
In Default Constructor Of TeachingBeeStudent Class

How to do Constructor Chaining In Java?

Constructor Chaining In java can be done using two ways:

  1. this keyword: If we want to chain constructors present within same class this keyword is used.
  2. super keyword: If we want to chain constructors of parent class super keyword can be used.

Constructor Chaining Within The Same Class

Let’s look into example and understand constructor chaining within same class.

// Constructor Chaining Within the Same Class

public class Employee {
  // Default constructor
  Employee() {

   // Constructor Chaining Within the Same Class
    this(1004);
    System.out.println("In Default constructor Of Employee Class");
  }

  // Parameterized constructor with Integer Parameter
  Employee(int employeeId) {

   // Constructor Chaining Within the Same Class
    this("employeeName");
    System.out.println("In Parameterized constructor With Integer Parameter: " + employeeId);
  }

  // Parameterized constructor with String Parameter
  Employee(String employeeName) {
    System.out.println("In Parameterized constructor With String Parameter: " + employeeName);
  }

  public static void main(String arg[]) {
    Employee employeeObj = new Employee();
  }
}

Output:

In Parameterized constructor With String Parameter: employeeName
In Parameterized constructor With Integer Parameter: 1004
In Default constructor Of Employee Class

  • In the above program when Employee class object is created, the default constructor of Employee Class is called.
  • Within default constructor, parametrised constructor with int parameter is called using this(1004); statement. Thus control goes into that constructor before print statement is invoked.
  • Similarly, within parametrised constructor with int parameter, constructor with string parameter is called, passing control to string type parametrised constructor.
  • Thus, print statement of string type parametrised constructor is called first, followed by int type parametrised constructor and lastly default constructor.

Constructor Chaining From Different Class

This type of constructor chaining in java occurs using inheritance. Using super keyword we can call constructor of parent class from derived class.Let’s understand this using example.

Parent Class

//Constructor Chaining From Different Class
// Parent Class

class Employee {
  // Default constructor 
  Employee() {
    System.out.println("In Default constructor Of Employee Class");
  }

  // Parameterised constructor with String Parameter
  Employee(String employeeName) {
    System.out.println("In Parameterised constructor Of Employee Class With String Parameter: " + employeeName);
  }

}

Derived Class

//Constructor Chaining From Different Class
// Derived Class  

public class SoftwareDeveloper extends Employee {

  // Default constructor 
  SoftwareDeveloper() {
    super("employeeName");
    System.out.println("In Default constructor Of SoftwareDeveloper Class");
  }

  public static void main(String arg[]) {
    SoftwareDeveloper softwareDeveloperObj = new SoftwareDeveloper();
  }
}

Output:

In Parameterised constructor Of Employee Class With String Parameter: employeeName
In Default constructor Of SoftwareDeveloper Class

  • In the above program when SoftwareDeveloper class object is created without paramters, the default constructor of SoftwareDeveloper Class is called.
  • Within default constructor, parametrised constructor of parent class i.e Employee class is called using super(“employeeName”); statement. Thus control goes into parent class constructor before print statement of derived class constructor is invoked.
  • Thus, print statement of parameterised parent class constructor is invoked first and then derived class default constructor is called

By default, JVM invokes constructor chaining the moment new object is created. JVM calls the constructor for the class, and that constructor will invoke the superclass constructor.
Whether it is single class or inheritance, in either case the final point to this chain will always be Object Class constructor, as it is the parent class of all the classes in java by default. In other words, it is the topmost class of java.

Rules of Constructor Chaining in Java

Some of the rules that need to be followed for Constructor Chaining in Java are:

Necessity of Constructor Chaining In Java

  • Code Maintenance and less duplicated code: Constructor chaining in java can be used for maintenance of code, the idea is to create one code line only once, and there is no chance of missing something while editing your methods and both ending up being distinct.
  • No new Object creation: The constructor calling itself doesn’t create a new object It uses the current operating object as a reference to a different constructor. There’s no need for the new keyword, there is no new object creation . It’s basically like just calling a method within your constructor, but the method is also the constructor.

Conclusion

In this article, we discussed constructors chaining in Java. Firstly, we explained what is called constructors chaining. Then, we showed how to do this with constructors within the same and different class. We also discussed rules of constructor chaining in java and benefits of the same.

Got a question or just want to chat? Comment below or drop by our forums, where a bunch of the friendliest people you’ll ever run into will be happy to help you out!

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

ascii value in java

Print ASCII Value in Java

In this article we will into the ASCII table in C, exploring its various character sets—from control characters to printable characters, including letters, digits, and special symbols—and demonstrates how to

data hiding in java

Data Hiding In Java

In this article we will discuss data hiding in Java which is an important concept in object-oriented programming. We will cover So let’s get started. What is Data Hiding in

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In