What is the use of overloading in java?
Answers
Method Overloading is used for creating a method with the same name as an existing method in a class.
Hence, method overloading allows us to have multiple methods with the same name within a class.It is similar to constructor overloading.
Eg:
Consider two argument list, argument list of a method add(int a, int b) having two parameters is different from the argument list of the method add(int a, int b, int c) having three parameters.
There are 3 Ways to overload a method
1. Number of parameters.
Eg:
add(int, int)
add(int, int, int)
2. Data type of parameters.
Eg:
add(int, int)
add(int, float)
3.Sequence of Data type of parameters.
Eg:
add(int, float)
add(float, int)
The purpose of overloading
Eg:
There is a method which performs addition function, but cannot predict the number of inputs.
It is also impossible to declare and define new methods for each and every number of inputs.
Now without using method overloading, programmer needs to write the code given as below :
int add2Var(int a, int b)
int add3Var(int a, int b, int c)
int add4Var(......
To solve this,concept of method overloading was implemented.
Method Overloading declares a single method and you can overload it to perform the same addition function with different number of inputs.
By using method overloading,
int add(int a, int b)
int add(int a,int b, int c)
int add(......)
In the above you don't need to declare the method names separately.