DEV Community

PRIYA K
PRIYA K

Posted on

Constructor Chaining in Java

Read gfg

Constructor chaining is the process of calling one constructor from another constructor within the same class or from a parent class. It helps reduce code duplication and improves code readability by reusing existing constructor logic. Constructor chaining is achieved using the this() and super() keywords.
Uses this() for constructors within the same class.
Uses super() to call a parent class constructor.

Types of Constructor Chaining in Java**

  1. Constructor Chaining Within the Same Class Using this()**

Constructor chaining within the same class occurs when one constructor calls another constructor of the same class using the this() keyword. It is mainly used to reuse initialization code between multiple constructors.
this() calls another constructor of the same class.
It must be written as the first statement in a constructor.

Rules of constructor chaining :
The this() expression should always be the first line of the constructor.
There should be at-least be one constructor without the this() keyword .
Constructor chaining can be achieved in any order.

What happens if we change the order of constructors?
Nothing, Constructor chaining can be achieved in any order

2. Constructor Chaining Using super() (Parent Class)

Constructor chaining between classes occurs when a child class constructor calls the parent class constructor using the super() keyword. It ensures that the parent class object is initialized before the child class object.

It must be the first statement in the child class constructor.
Used in inheritance to initialize superclass members.
Enter fullscreen mode Exit fullscreen mode

Syntax

class Parent {
    Parent() {
     // parent constructor
     }
    }

    class Child extends Parent {
    Child() {
    super();
    // child constructor
     }
    }
Enter fullscreen mode Exit fullscreen mode
Note : Similar to constructor chaining in same class, super() should be the first line of the constructor as super class's constructor are invoked before the sub class's constructor.
Enter fullscreen mode Exit fullscreen mode

Constructor Chaining Using Initialization Block

An initialization block is a block of code that executes before constructors whenever an object is created. It is useful when the same code needs to run for multiple constructors.

Used to initialize common resources.
Multiple initialization blocks execute in the order they are defined.
NOTE: If there are more than one blocks, they are executed in the order in which they are defined within the same class
Enter fullscreen mode Exit fullscreen mode

Advantages of Constructor Chaining

Avoids code duplication
Improves code readability
Makes constructor management easier
Provides better object initialization
Supports inheritance-based initialization
Enter fullscreen mode Exit fullscreen mode

Top comments (0)