0% found this document useful (0 votes)
17 views20 pages

Constructor Chaining in Java Explained

The document discusses constructor chaining in Java, which is the process of calling one constructor from another constructor of the same class or parent class. Constructor chaining avoids duplicate code and makes the code more readable. It can be done within a class using the this() keyword or between classes using the super() keyword. The order of constructor chaining does not matter. Initialization blocks can also be used to execute common code before any constructor.

Uploaded by

singharushi948
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views20 pages

Constructor Chaining in Java Explained

The document discusses constructor chaining in Java, which is the process of calling one constructor from another constructor of the same class or parent class. Constructor chaining avoids duplicate code and makes the code more readable. It can be done within a class using the this() keyword or between classes using the super() keyword. The order of constructor chaining does not matter. Initialization blocks can also be used to execute common code before any constructor.

Uploaded by

singharushi948
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dr Bharti Sharma

Constructor Chaining In Java with Examples

Constructor chaining is the process of calling one constructor from another constructor with respect to current
object.
One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by
means of constructor overloading) and make code more readable.

Constructor chaining can be done in two ways:

 Within same class: It can be done using this() keyword for constructors in the same class
 From base class: by using super() keyword to call the constructor from the base class.

Constructor chaining occurs through inheritance. A sub-class constructor’s task is to call super class’s constructor
first. This ensures that the creation of sub class’s object starts with the initialization of the data members of the
superclass. There could be any number of classes in the inheritance chain. Every constructor calls up the chain till
the class at the top is reached.

Why do we need constructor chaining?

This process is used when we want to perform multiple tasks in a single constructor rather than creating a code
for each task in a single constructor we create a separate constructor for each task and make their chain which
makes the program more readable.
Dr Bharti Sharma

Constructor Chaining within the same class using this() keyword:


Dr Bharti Sharma

 Java

// Java program to illustrate Constructor Chaining

// within same class Using this() keyword

class Temp

// default constructor 1

// default constructor will call another constructor

// using this keyword from same class

Temp()

// calls constructor 2
Dr Bharti Sharma

this(5);

[Link]("The Default constructor");

// parameterized constructor 2

Temp(int x)

// calls constructor 3

this(5, 15);

[Link](x);

}
Dr Bharti Sharma

// parameterized constructor 3

Temp(int x, int y)

[Link](x * y);

public static void main(String args[])

// invokes default constructor first

new Temp();

Output:
75
Dr Bharti Sharma

5
The Default constructor
Rules of constructor chaining :
1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword (constructor 3 in above
example).
3. 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
 Java

// Java program to illustrate Constructor Chaining

// within same class Using this() keyword

// and changing order of constructors

class Temp

{
Dr Bharti Sharma

// default constructor 1

Temp()

[Link]("default");

// parameterized constructor 2

Temp(int x)

// invokes default constructor

this();

[Link](x);
Dr Bharti Sharma

// parameterized constructor 3

Temp(int x, int y)

// invokes parameterized constructor 2

this(5);

[Link](x * y);

public static void main(String args[])

{
Dr Bharti Sharma

// invokes parameterized constructor 3

new Temp(8, 10);

Output:
default
5
80
NOTE: In example 1, default constructor is invoked at the end, but in example 2 default constructor is invoked
at first. Hence, order in constructor chaining is not important.

Constructor Chaining to other class using super() keyword :


 Java

// Java program to illustrate Constructor Chaining to


Dr Bharti Sharma

// other class using super() keyword

class Base

String name;

// constructor 1

Base()

this("");

[Link]("No-argument constructor of" +

" base class");

}
Dr Bharti Sharma

// constructor 2

Base(String name)

[Link] = name;

[Link]("Calling parameterized constructor"

+ " of base");

class Derived extends Base

{
Dr Bharti Sharma

// constructor 3

Derived()

[Link]("No-argument constructor " +

"of derived");

// parameterized constructor 4

Derived(String name)

// invokes base class constructor 2

super(name);
Dr Bharti Sharma

[Link]("Calling parameterized " +

"constructor of derived");

public static void main(String args[])

// calls parameterized constructor 4

Derived obj = new Derived("test");

// Calls No-argument constructor

// Derived obj = new Derived();

}
Dr Bharti Sharma

Output:
Calling parameterized constructor of base
Calling parameterized constructor of derived
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.

Alternative method : using Init block :


When we want certain common resources to be executed with every constructor we can put the code in the init
block. Init block is always executed before any constructor, whenever a constructor is used for creating a new
object.
Example 1:
 Java

class Temp

// block to be executed before any constructor.


Dr Bharti Sharma

[Link]("init block");

// no-arg constructor

Temp()

[Link]("default");

// constructor with one argument.

Temp(int x)
Dr Bharti Sharma

[Link](x);

public static void main(String[] args)

// Object creation by calling no-argument

// constructor.

new Temp();

// Object creation by calling parameterized

// constructor with one parameter.


Dr Bharti Sharma

new Temp(10);

Output:

init block
default
init block
10
NOTE: If there are more than one blocks, they are executed in the order in which they are defined within the
same class. See the ex.
Example :

 Java

class Temp
Dr Bharti Sharma

// block to be executed first

[Link]("init");

Temp()

[Link]("default");

Temp(int x)

[Link](x);
Dr Bharti Sharma

// block to be executed after the first block

// which has been defined above.

[Link]("second");

public static void main(String args[])

new Temp();

new Temp(10);

}
Dr Bharti Sharma

Output :
init
second
default
init
second
10
This article is contributed by Apoorva singh. If you like GeeksforGeeks and would like to contribute, you can
also write an article using [Link] or mail your article to review-team@[Link]. See
your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic
discussed above.

Like175
Previous
Copy Constructor in Java
Next

Common questions

Powered by AI

Constructor chaining affects object-oriented design patterns by enforcing structured initialization within inheritance hierarchies. It ensures that superclass initializations precede subclass-specific setup, which is critical for adhering to principles like Liskov Substitution. This chaining supports polymorphism by maintaining state consistency across an inheritance chain while promoting code reuse across constructors, aligning with principles such as DRY (Don't Repeat Yourself). As a result, it can simplify implementations of patterns like Factory or Template methods that rely heavily on object instantiation and initialization sequences .

If `super()` is omitted from a subclass constructor when the superclass requires parameters, it leads to a compilation error. Java automatically tries to insert a no-argument `super()` call unless explicitly provided otherwise, which fails if no such constructor exists in the superclass. Therefore, it is crucial to explicitly call the appropriate superclass constructor in such cases to ensure correct object initialization .

Constructor chaining within a single class decentralizes the logic into multiple constructors with different parameter lists, reducing complexity. This allows for clear separation of setup tasks and eliminates redundant code blocks, thus improving the ease of code maintenance. Each constructor handles a specific aspect of an object's initialization, making it easier to update and troubleshoot .

Initialization blocks in Java are executed before any constructor. When combined with constructor chaining, they ensure that certain common code executes irrespective of which constructor is involved in the object creation. This helps to keep constants and shared setup logic centrally located and reduces the likelihood of errors by ensuring consistent initialization behavior across all constructors .

The `super()` call must be the first line in a subclass constructor to ensure that the superclass's constructor logic executes before any subclass-specific initialization occurs. This order is crucial for correctly establishing the base class's state before the subclass can manipulate or extend it, preserving the integrity of the object hierarchy and ensuring consistent object state .

Init blocks in Java are used to perform common setups across different constructors without code duplication. These blocks execute before any constructor is called when a new object is created. If multiple init blocks are defined, they execute sequentially in the order they are defined, regardless of which constructor is called subsequently .

In Java, `this()` and `super()` must be the first statement in a constructor that uses them, ensuring proper initialization sequence. For a constructor using `this()`, at least one constructor in the class does not invoke `this()`, stopping infinite recursion. Similarly, while chaining from a base class using `super()`, it should appear first so that the base class constructor executes before the subclass constructor .

Constructor chaining in Java allows multiple tasks to be performed using multiple constructors with different parameters, rather than creating a single constructor with complex logic. By using `this()` and `super()` keywords, the program avoids code duplication by reusing code blocks across different constructors. This leads to more maintainable and readable code as it separates different initialization tasks into distinct constructors and connects them logically .

Constructor chaining between superclass and subclass is achieved using the `super()` keyword, which allows a subclass constructor to invoke a specific constructor from its superclass. This ensures that a superclass's constructor is executed before the subclass's own constructor logic, initializing any inherited properties correctly. This approach maintains the inheritance hierarchy and proper initialization order across involved classes .

When using constructor chaining, changing the order of constructors does not impact the functionality as long as the `this()` keyword is placed correctly as the first line within a constructor. The process executed remains the same as it depends on which constructor is called first from an object instantiation, thus maintaining the same execution logic and results .

You might also like