Constructor Chaining in Java

Constructor Chaining in Java

29 Mar 2024
Beginner
200 Views
17 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Constructor Chaining in Java: An Overview

Constructor Chaining in Java plays a very important role in a Java Program, especially when we are dealing with multiple constructors in a class. In this Java Tutorial, we'll explore What is Constructor Chaining in Java?, What is the use of Constructor Chaining?, Constructor Chaining in Java with Examples. To enhance your knowledge in Java, we advice you to enroll in our Java Certification Program.

What is Constructor Chaining in Java?

We assume you already know what areConstructors in Java. They are the special methods which help in initializing newly created objects. One of the concepts related to constructors is Constructor Chaining.

  • Constructor Chaining is a mechanism in Java where one constructor calls another constructor within the same class or in its superclass.
  • It works like a chain, where one constructor leads to another and the execution of multiple constructors occurs in a sequence.
  • To chain constructors within the same class, we use this() keyword and super() to call constructor from the parent class.

Types of Constructor Chaining

  1. Chaining within the same class this type of constructor chaining in Java, chaining occurs within the same class, that is, a constructor calls another constructor of the same class to which it belongs.
  2. Syntax

        public class MyClass {
        // Constructor with parameters
        public MyClass(int param1, String param2) {
            // Some initialization or processing
            
            // Call another constructor within the same class
            this(param1);
            
            // Additional initialization or processing
        }
        
        // Constructor with a different set of parameters
        public MyClass(int param1) {
            // Some initialization or processing
            
            // Additional initialization or processing
        }
    }    
  3. Chaining with Superclass Constructors- With the help of Inheritance, a subclass can inherit from a superclass. Constructor Chaining with superclass constructors is when a constructor in a subclass calls a constructor from its superclass using the ‘super()’ keyword. This ensures proper execution of initialization tasks in both superclass and subclass when an object is created in the subclass.
  4. Syntax

        public class Subclass extends Superclass {
        // Constructor with parameters
        public Subclass(int param1, String param2) {
            // Call superclass constructor with parameters
            super(param1, param2);
            
            // Additional initialization or processing
        }
    }    

How Constructor Chaining Works in Java?

Constructor Chaining in Java can be seen as a teamwork approach where each constructor helps set up the object, and together they ensure everything is ready for action. For instance, if you have multiple constructors in a class, one constructor can pass the job of setting up an object to another constructor within the same class or in its parent class.
Constructor Chaining in Java

Example on our Java Compiler

    public class MyClass {
    private int value1;
    private String value2;

    // Constructor with parameters
    public MyClass(int value1, String value2) {
        // Call another constructor within the same class
        this(value1);

        // Some initialization or processing
        this.value2 = value2;

        // Additional initialization or processing
        System.out.println("Constructor with int and String parameters called.");
    }

    // Constructor with a different set of parameters
    public MyClass(int value1) {
        // Some initialization or processing
        this.value1 = value1;

        // Additional initialization or processing
        System.out.println("Constructor with int parameter called.");
    }

    public void displayValues() {
        System.out.println("Value1: " + value1);
        System.out.println("Value2: " + value2);
    }

    public static void main(String[] args) {
        // Creating an instance of MyClass
        MyClass obj = new MyClass(10, "Hello");

        // Displaying values
        obj.displayValues();
    }
}    

In the above example,

  • There are two constructors in the class MyClass, one has two parameters and another only one.
  • The constructor that has two parameters, int and string, calls the other constructor that has only one parameter, int using the this() keyword.

Output

Constructor with int parameter called.
Constructor with int and String parameters called.
Value1: 10
Value2: Hello

Chaining Constructors in Superclasses

Constructor chaining is not limited to classes with a single level of inheritance. It can also be used in subclasses to chain constructors from their superclass.
Consider the following example in the Java Online Compiler:
    class Vehicle {
    private String brand;
    private String model;

    // Constructor with parameters
    public Vehicle(String brand, String model) {
        this.brand = brand;
        this.model = model;
        System.out.println("Vehicle constructor called with brand: " + brand + ", model: " + model);
    }
}

class Car extends Vehicle {
    private int year;

    // Constructor with parameters
    public Car(String brand, String model, int year) {
        super(brand, model); // Call superclass constructor with parameters
        this.year = year;
        System.out.println("Car constructor called with brand: " + brand + ", model: " + model + ", year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of Car
        Car car = new Car("Toyota", "Corolla", 2020);
    }
}    

In the above example,

  • There is a superclass Vehicle, which has attributes as brandand model.
  • It has a subclass Car, with another attribute year.
  • Using the super() keyword, the constructor of the Car class calls the constructor of Vehicle class.
  • In the main()method, when an instance of Caris created, both the constructors of Car and Vehicle are called.

Output

Vehicle constructor called with brand: Toyota, model: Corolla
Car constructor called with brand: Toyota, model: Corolla, year: 2020

Implicit Super Constructor Call

If there is a case where the superclass constructor is not directly called by the subclass constructor, the Java compiler will automatically do that and call the superclass’s no-argument constructor.

Example:

    class Superclass {
    int num;

    // Superclass constructor
    public Superclass() {
        System.out.println("Superclass constructor called.");
        num = 10;
    }
}

class Subclass extends Superclass {
    // Subclass constructor
    public Subclass() {
        // Call to superclass constructor
        super();
        System.out.println("Subclass constructor called.");
    }

    // Method to display the value of num
    public void display() {
        System.out.println("Value of num in superclass: " + num);
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object of Subclass
        Subclass obj = new Subclass();

        // Calling display method
        obj.display();
    }
}    

Explanation:

  • We have two classes here, ‘Superclass’ and ‘Subclass’ in our Java Online Editor.
  • Subclass inherits from Superclass.
  • Superclass has a default constructor that initializes the variable ‘num’ to 10.
  • Subclass does not define any constructors explicitly.
  • When an object of Subclass is created (‘Subclass obj = new Subclass();’), the constructor of Superclass is implicitly called before the constructor of Subclass.
  • The Java compiler calls the superclass constructor implicitly by itself and ‘Superclass’ execution occurs first, before the execution of the ‘Subclass’.

Output

Superclass constructor called.
Subclass constructor called.
Value of num in superclass: 10

Benefits of Constructor Chaining

  1. Code Reusability-Constructor Chaining allows you to reuse code when there are multiple constructors by calling one constructor from another within the same class or its superclass instead of duplicating it.
  2. Organization- When we chain constructors, we get a more logically organized code. The code becomes more readable.
  3. Flexibility- Constructor Chaining allows you to define multiple constructors with different sets of parameters or initialization tasks making the process of object initialization more flexible. Moreover, constructor can be chosen based on specific requirements, making the interface more versatile.
  4. Initialization Order- When one constructor calls another, it makes sure that any common or superclass initialization tasks are executed before the specific tasks of the current constructor, ensuring that initialization tasks are performed in the correct order.

Rules of Constructor Chaining

Here are some rules to keep in mind to ensure that constructor chaining is proper and correct:
  1. First Statement- The first statement in the constructor must be the call to another constructor, that is, ‘this()’ or ‘super()’.
  2. One Call constructor can only call one another constructor, be it from the same class or its superclass.
  3. No Circular Chains- Constructor chaining must be done in a way that it should not create a circular chain, where one constructor indirectly calls itself.

Using the init() method for Constructor Chaining

There is an alternate method used for Constructor Chaining in Java which is the init() method. Using the init block too, you can use Constructor Chaining in Java. Just see the working in our Java Playground.

Example

    class MyClass {
    private int value1;
    private String value2;

    // Constructor with parameters
    public MyClass(int value1, String value2) {
        // Perform some initialization or processing
        init(value1, value2);
        System.out.println("Constructor with int and String parameters called.");
    }

    // Constructor with a different set of parameters
    public MyClass(int value1) {
        // Perform some initialization or processing
        init(value1, "Default");
        System.out.println("Constructor with int parameter called.");
    }

    // Private initialization method
    private void init(int value1, String value2) {
        this.value1 = value1;
        this.value2 = value2;
        // Additional initialization or processing can be done here
    }

    public void displayValues() {
        System.out.println("Value1: " + value1);
        System.out.println("Value2: " + value2);
    }

    public static void main(String[] args) {
        // Creating an instance of MyClass
        MyClass obj1 = new MyClass(10, "Hello");
        MyClass obj2 = new MyClass(20);

        // Displaying values
        obj1.displayValues();
        obj2.displayValues();
    }
}    

In the above example,

  • We have used the private init() method for initializing the instance variables.
  • There are two constructors in MyClass and both of them call the init method with parameters needed.

Output

Constructor with int and String parameters called.
Constructor with int parameter called.
Value1: 10
Value2: Hello
Value1: 20
Value2: Default 

Why do we need Constructor Chaining?

Constructor Chaining is very important in Java when we are working with multiple constructors with different parameters. Chances of code repetition decreases when we chain them together and it becomes more organized that way. We can easily have one constructor call another, instead of writing the same setup code in every constructor of a class.
Summary
Through this Java Tutorial, we hope you got a knack of what Constructor Chaining is, how it works and what are its benefits. Understanding how Constructor chaining works in Java, will surely help you get better with your Java programs. To have more expertise in Java, do consider enrolling in our Java Course.

FAQs

Q1. When do we use constructor chaining in Java?

Constructor Chaining is used to avoid code duplication and ensure proper initialization by allowing one constructor to call another within the same class or its superclass improving code creation and organization.

Q2. How to call one constructor from another constructor in Java?

To call one constructor from another in Java:
  1. Use ‘this()’ keyword with appropriate arguments to call another constructor in the same class.
  2. Ensure that the call to another constructor is the first statement in the constructor where it is called.

Q3. What is the use of Constructor Chaining?

Constructor chaining in Java allows one constructor to call another constructor within the same class or its superclass, enabling code reuse and ensuring proper initialization of objects.

Q4. What is the difference between method chaining and constructor chaining in Java?

Method chaining involves calling multiple methods on the same object in a single line to perform a series of operations, whereas constructor chaining involves calling one constructor from another within the same class or its superclass during object creation to initialize the object.
Share Article
Live Training Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this