What is Constructor Chaining in Java ?

  • When a constructor of a class is called from another constructor of the same class, this is known as ‘Constructor Chaining’.
  • If we have two or more constructors in a class and we want to call one constructor from another, then we can do this by using ‘this()’ statement.
  • ‘this()’ calls the appropriate constructor, according to the parameter passed to it.

NOTE : this() must be the first statement in the calling constructor.

Example :

class Chaining {
Chaining() //default constructor
{
System.out.println(“Default Constructor Called”);
}
Chaining(int i) // parameterized cons (with one argument)
{
this(); // calling Default Constructor
System.out.println(“One Argument Constructor is Called with argu : “+i);
}
Chaining(String s1,String s2) // parameterized cons (with two argument)
{
this(1); // calling one argu Constructor
System.out.println(“Two Argument Constructor is Called with argu : “+s1+” and “+s2);
}
public static void main(String[] args) {
Chaining c= new Chaining(“Programming”,”Prashn”);
}
} // end of class


Output :

 

Default Constructor Called
One Argument Constructor is Called with argu : 1
Two Argument Constructor is Called with argu : Programming and Prashn

Related Post

Leave a Reply

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


The reCAPTCHA verification period has expired. Please reload the page.