If a class have multiple methods by the same name but different parameters it is known as method overloading.
If we have to perform only one operation, having the same name of the methods increases the readability of the program. Highlighted one is the advantage of the method overloading.
The different way to overload the method:
- By changing number of arguments
- by changing the data type
Example of method overloading by changing the number of arguments:
class Calculation
{
void sum(int a,int b){System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
Output:
30
40
Anonymous User
01-Jun-2015ANkita gupta
01-Jun-2015Output:21.0
40
Now, question arising why method overloading is not possible by changing the return type of method
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called.
Can we overload main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading.
Let's see the simple example:
Output:main() method invoked
10