Home Java Overview Maven Tutorials

Monday, 19 April 2021

Constructor Chaining In java

What is Constructor chaining in JAVA

Definition :-

The process of invoking a sequence of constructors upon initialization of a class object is called constructor chaining.
Constructor chaining is useful when you want to invoke multiple constructors, one after another, by initializing only one instance.

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

package ChandanPack1;

class A
System.out.println("I am inside A class constructor");
A(int x)
this(2, 4);
System.out.println("Superclass second constructor" + " " +x);
A(int l, int m)
System.out.println("multiply is " + " " + (l*m));

public class BajiPractice extends A
System.out.println("i am inside first constructor");
BajiPractice(int x)
this(2, 80);
System.out.println("number is:->" + " "+ x);
BajiPractice(int a, int b)
System.out.println("the sum is" + " " +(a+b));
public static void main(String args[])
System.out.println("constructor chaining started");
BajiPractice obj = new BajiPractice();

Output:- constructor chaining started
multiply is 8
Superclass second constructor 0
I am inside A class constructor
the sum is 82
number is:-> 10
i am inside first constructor

No comments:

Post a Comment