Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Constructor Chaining in Java

In Object Oriented Languages such as Java, Constructors play a crucial role in the initialization of the Objects. A constructor in Java is defined as a special method that is used to initialize the objects of a class. When we create an object, the constructor is called, which initializes the member variables and other state information. Constructor chaining in Java can be defined as the technique in which a constructor invokes another constructor of the same class or of a parent class. Let us learn about Constructor Chaining in Java in detail along with examples.

Constructor Chaining in Java

Constructor chaining in Java is the process of calling one constructor from another constructor of the same class or of its parent class. In Java, a constructor can call another constructor using the "this" and “super” keywords. This Constructor Chaining in Java allows the developer to reuse the code and in avoiding redundancy in the initialization of the objects.

Benefits of Constructor Chaining in Java

Constructor chaining in Java provides several benefits:

  • Code reuse: The Constructor Chaining in Java helps the Developers in the reusability of code and avoiding redundancy in the initialization of objects. Developers may write the code once and call it from other constructors rather than writing the same code in many constructors.
  • Flexibility: Developers can create various constructors with different arguments by using constructor chaining in java. Developers may create constructors with various parameter combinations by chaining constructors without writing duplicate code.
  • Simplified code: Constructor chaining in java reduces code complexity and makes it easier to understand and maintain. Developers can break down complex initialization code into smaller, more manageable chunks rather than putting it all in a single constructor.

How to Implement Constructor Chaining in Java

Constructor chaining in Java is performed by using the "this" and "super" keywords. The "this" keyword is used to invoke another constructor inside the same class, whereas the "super" keyword invokes a constructor within the parent class.

In this section, we will show you how to use constructor chaining in Java.

Example 1: Constructor Chaining in Java using "this" Keyword
This example will demonstrate the constructor chaining in java using the "this" keyword. The class has two constructors – one that takes no arguments and one that takes a String parameter. The constructor with no arguments calls the constructor with a String parameter using the "this" keyword.

Code:

class PrepBytes {  
   
    //default constructor  
    PrepBytes(){  
        this("PrepBytes");  
        System.out.println("Default constructor is called.");  
    }
   
    //parameterized constructor  
    PrepBytes(String str){  
        System.out.println("Parameterized constructor");  
    }
   
    public static void main(String args[]){  
        PrepBytes obj = new PrepBytes();  
    }  
}  

Output:

Parameterized constructor 
Default constructor is called.

Explanation:
In this example, the constructor with no arguments calls the constructor with an integer parameter using the "this" keyword. Here, we have created the instance of the class “PrepBytes” without passing any parameter to it. This will invoke the default constructor. Then, the default constructor calls the parameterized constructor because we have use the this(“PrepBytes”). After this line, all the statements of the Parameterized Constructor are executed and then the control returns to the default constructor. Now, all the Statements in Default Constructor are executed and the object is initialized successfully. Here is the complete flow of the program.

Example 2: Constructor Chaining in Java using the "super" Keyword
The following example demonstrates constructor chaining in Java using the "super" keyword.

Code:

//parent class  
class Parent{  
    //base class default constructor  
    Parent() {  
        System.out.println("Base Class Default Constructor");  
    }  
}  


//derived class  
class Child extends Parent {
   
    //derived class default constructor  
    Child(){  
        this("Java", "Python");  
        System.out.println("Child Class Default Constructor");  
    }
   
    //derived class parameterized constructor  
    Child(String str1, String str2) {  
        super();  
        System.out.println("Child Class Parameterized Constructor");  
    }  
}


class ConstructorChaining{
    public static void main(String args[]){  
        Child obj = new Child();  
    }  
}  

Output:

Base Class Default Constructor
Child Class Parameterized Constructor
Child Class Default Constructor

Explanation:
In the above example, we have defined a Parent class with Default Constructor only. We have also defined a Child class which is extending the Parent Class. This Child Class has one Default Parameter and another Parameterized constructor that takes two String Parameters.

When we initialized the object of the Child class in the Main method without passing any parameters. It calls the default parameter of the Child class, which in turn calls the Parameterized Constructor of the Child Class. Now the Parameterized Constructor calls the Default Constructor of the Parent class by using the super() statement. Now all the statements of the Default Constructor of the Parent Class are executed and the control returns back to the Parameterized Constructor of the Child Class. After executing all the statements of the Parameterized Constructor, the control returns to the Default Constructor of the Child Class. Now, the rest of the statements of this Default Constructor are executed and the object is initialized successfully.

The complete flow of the above program is shown below image.

Conclusion
Constructor chaining in Java is a powerful technique that allows developers to reuse code and avoid redundancy in the initialization of objects. By calling one constructor from another constructor, developers can create constructors with different parameter combinations without duplicating code. Constructor chaining simplifies code and makes it easier to read and maintain. In this article, we provided an overview of constructor chaining in Java, its benefits, and how to implement it with code examples.

Frequently Asked Questions (FAQs)

Here are some Frequently Asked Questions on Constructor Chaining in Java.

Ques 1. Can a constructor call multiple constructors in Java?
Ans. Yes, a constructor can call multiple constructors using constructor chaining.

Ques 2. Is constructor chaining mandatory in Java?
Ans. No, constructor chaining is not mandatory in Java, but it is a useful technique for reducing code duplication and simplifying object initialization.

Ques 3. What will happen if we change the order of the constructors in Java?
Ans. Nothing will happen, Constructor Chaining in Java can be achieved in any order.

Ques 4. Can constructor chaining be done in multiple levels of inheritance?
Ans. Yes, constructor chaining can be done in multiple levels of inheritance by calling constructors in the parent and grandparent classes.

Ques 5. Can constructor chaining be used with static constructors in Java?
Ans. No, constructor chaining cannot be used with static constructors in Java.

Ques 6. Can a constructor call a static method in Java?
Ans. Yes, a constructor can call a static method in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *