Site icon JavaGoal

Constructor chaining in java

Here is the table content of the article will we will cover this topic.
1. What is Constructor chaining in java?
2. How to do Constructor Chaining?
3. How Does Constructor Chaining Work?
4. Rules of Constructor Chaining in Java?
5. The need of Constructor Chaining?

Video in hindi – JavaProgrammmingGoal

What is Constructor chaining in java

As you know a method can call another method. Like a method, a constructor can call another constructor and this is known as Constructor chaining in java. In java, A constructor can call the constructor of the superclass and the constructor defined in the same class. In this article, we will read how we can achieve constructor overloading and what the rules we should follow.

Example of constructor chaining

We will discuss the constructor chaining in Java. In this Java program, we will show how to call constructor using both this() keyword and super() keyword.

class Person
{
    public Person()
    {
        System.out.println("Person class no-args constructor called");
    }
    public Person(String name)
    {
        System.out.println("Person class parameterized constructor called by "+name);
    }
}
public class Record extends Person
{
    public Record()
    {
        this("Record class");
        System.out.println("Record class no-args constructor called");
    }
    public Record(String name)
    {
        super();
        System.out.println("Record class parameterized constructor called by "+name);
    }
    public static void main(String args[])
    {
        Record c = new Record();
    }
}

Output: Person class no-args constructor called
Record class parameterized constructor called by Record class
Record class no-args constructor called

In the above example, we are creating two classes those have some constructors. Here we are using this() keyword to call the constructor of the same class(Record class) and super() keyword to call the constructor of Parent class(Person class).

How to do Constructor Chaining?

We can do Constructor chaining by use of two keywords .

  1. By this keyword (within the same class)
  2. By super keyword (to call the superclass constructor)

1. this keyword: By using this keyword, you can construct constructor chaining in the same class. This keyword must be the first statement in the constructor. otherwise, it will throw a compilation error.

public class Student 
{
   // default constructor 
   Student()
   {
        this(123);
   		System.out.println("This is default constructor");
   }
  
   // parameterized construction have int type parameter
   Student(int a)
   {
      this("Hello");
      System.out.println("Parameterized constructor");
      System.out.println("It's called form default constructor");
   }
   Student(String a)
   {
	   System.out.println("Parameterized constructor"); 
	   System.out.println("It's called by default constructor having int type parameter");
   }
  
   public static void main (String arg[])
   { 
	   Student n = new Student();
   }
}

Output: Parameterized constructor
It’s called by default constructor having int type parameter
Parameterized constructor
It’s called form default constructor
This is default constructor

2. Super keyword:
NOTE: Before starting the super keyword, you should have knowledge about inheritance. If you want to read inheritance you can read the topic inheritance
By using of super keyword, you can construct constructor chaining outside the class. You can class base class constructors. The super keyword must be the first statement in the constructor. otherwise, it will throw a compilation error.

class BaseClass 
{
  // default constructor 
  BaseClass()
  {
    System.out.println("This is default constructor of Base class");
  }
  
  // parameterized construction have int type parameter
  BaseClass(String a)
  {
      System.out.println("This is parameterized constructor of base class.");
      System.out.println("It is called form default constructor of derived class");
  }
  
}
  public class DerivedClass extends BaseClass
  {
    DerivedClass()
    {
      super("Hello"); 
      System.out.println("This is default constructor of Drived class");
    }  
          public static void main (String arg[])
          {
            DerivedClass n = new DerivedClass();
          }
}

Output:
This is parameterized constructor of base class. It is called form default constructor
This is default constructor of Derived class

How Does Constructor Chaining Work?

Whenever you call a constructor from another constructor by use of this() and super() keyword. It is called constructor chaining.
By default, JVM is dealing with the constructor chaining because if you are creating an object by a new keyword then JVM invokes the constructor of that class and that constructor invokes the superclass constructor.
Whether you are working with a single class or inheritance, the end of the chain will always be the Object’s class constructor. Because Object is the superClass and every class is inherited from the Object class by default.

Let’s discuss it with example. Here we are using inheritance and we will see how does the constructor work.

Here Orange lines are showing how the control follows goes to when one constructor is calling to another.
Black lines are showing how to control follow returned after the execution of constructor.

Step 1:  After the creation of an object by the new keyword (new Record()), the control flow directly jumps to the constructor of record class that is Record().

Step 2: The body of the Record() constructor is also calling the constructor of the same class by use of this() keyword. (this(“Record class”)). It will transfer the control to another constructor that is Record(String name).

Step 3: Now the super() keyword comes in the role. Here we are using the super() keyword that is calling the constructor of the parent class(Person). The super keyword is used without any parameter so it is calling the constructor of the superclass that is default constructor of Person..

Step 4:  As we said earlier, the end of the chain will always be the Object’s class constructor. So it invoking the constrctor of Object’s class.

Step 5: After execution of the constructor of Object class the control back returns to the caller constructor that is Record(String name).

Step 6: After completion of Record(String name) it returning the control back to Record() and so on.

Rules of Constructor Chaining in Java

1. this() keyword calls the constructor within class only. You can’t call this() keyword(Without arguments) from the default constructor. It shows the error “Recursive constructor invocation Record()”. Because it tries to call the default constructor again which is not possible.

2. super() keyword calls the constructor of Parent class. It invokes the constructor of the immediate parent class only.

3. this() and super() must be the first statement in the constructor. If you try to place them anywhere it will show compilation time error.

4. If you did not add super() keyword in a constructor then JVM automatically add it.

The need of Constructor Chaining?

Before discussing the need for constructor changing we must understand the need for constructor overloading.

As we know constructor is used to initializing the object. Whenever you create an object by new keyword then JVM invokes the constructor and initialize values in memory. Sometimes we want to initialize the objects in different ways and perform a different action. So, we overload the constructor.

But there may be chance when we want to perform multiple tasks by use of single constructor. Then we should make chaining of constructors.  Even we can do multiple task by different constructor, but they create a separate object for each task in memory.

You must familiar with the HashMap class in Java. In HashMap class we have multiple constructors. To understand the chaining of constructors we will take an example of two constructors.
HashMap(int initialCapacity) and HashMap(int initialCapacity, float loadFactor).
Here both constructors are defined for different tasks.

The first constructor is used when we want to initialize the capacity of HashMap, and we don’t want to provide the load factor in HashMap. In this case, the load factor is initialized automatically. This constructor invokes another constructor of HashMap and making chaining of the constructor.

The second constructor is used when we want to initialize the capacity of HashMap and want to set the load factor of HashMap. This contractor is called by the first one. Let understand with an example.

Exit mobile version