Constructor Overloading in Java

Like Method overloading , we can overload Constructors as well. The Same constructor declared with different parameters in the same class is known as constructor overloading.

Compiler differentiates which constructor is to be called depending upon the number of parameters and their sequence of data types but there are certain rules related to Constructor overloading which needs to be remembered while overloading constructor in Java.

like – One Constructor can only be called from inside of another Constructor and if called it must be the first statement of that Constructor.

 

Example of Constructor Overloading

In the below example we are overloading the Perimeter class constructor by changing the arguments list in the constructor.

Output:

From first constructor
Circle perimeter: 628.3185307179587
Rectangle perimeter: 600

 

Video Tutorial of Automation Testing:

 

 

Role of this() in Constructor Overloading

this() keyword is used to calling the default constructor from parameterized constructor. this() should always be the first statement in parameterized constructor body.

Output:

From first constructor
Circle perimeter: 628.3185307179587
Rectangle perimeter: 600

 

In the above code, creating object c3, the 3rd constructor is accessed. From 3rd , with “this(100)” statement, the 2nnd constructor is accessed. Again from 2nd, the 1st is accessed without the statement “this()”.

As per the parameter supplied to this(), the appropriate or corresponding constructor is accessed.

 

Rules for this() keyword

In java, there are some rules for using this() keyword. Please note these –

  1. this() should be the first statement in the constructor code, you are not allowed to write any statement before this() inside the constructor.
  2. Two this() statements are not possible in the same constructor code. Because it’s impossible to be both first statements in the constructor.
  3. this() is used to call the constructor present in the same class only, you can’t use this() to call a super class constructor.

 

0 Comment

Leave a Reply