How constructor overloading is performed in Java

As constructor is a special type of method, constructor can also be overloaded. Several constructors can be defined in the same class given that the parameters vary in each constructor. As an example for constructor overloading, let’s consider the following code segment:
In the above code segment we can see that the constructor Sqaure() is overloaded. One constructor accepts a single integer parameter and returns a single square with side s. Another constructor accepts two integer parameters and returns n number of squares each with side s.


Why overloading?
In Java, overloading provides the ability to define two or more methods with the same name. What is the use of that? For example, you want to define two methods, in which, one method adds two integers and the second method adds two floating point numbers. If there is no overloading, we have to create two different methods. One for adding two integers and the other for adding two floating point numbers. As the underlying purpose of the methods is same, why create methods with different name? Instead of creating two different methods, overloading allows us to define two methods with the same name.

Method Overloading:
Creating two or more methods in the same class with same name but different number of parameters or different types of parameters is known as method overloading. Let’s consider the following code segment which demonstrates method overloading:
In the above code segment, the method sum is overloaded. Java compiler decides which method to call based on the type of the parameters in the method call. For example, if the method is called as shown below:
The sum method with two integer parameters will be invoked and the output will be Sum of two integers is: 30. 
If the method is called as shown below:
The sum method with two float parameters will be invoked and the output will be Sum of two floats is: 2.7.
Note: It should be remembered that Java automatically performs type conversion from one type to another type. So, proper care should be taken while defining overloaded methods.


Take your time to comment on this article.


EmoticonEmoticon