Method Overloading
In OOP, we can define more than one method by the same name in a class. Those methods are
called OVERLOADED METHODS and this technique is known as Method Overloading.
Return type of the overloaded methods may be same or may not be same. But, either-
1. Number of parameters OR
2. Data Type of Parameters OR
3. Sequence of Parameters
Of the overloaded methods MUST BE DIFFERENT.
In method overloading, which one of the overloaded methods will be executed at runtime, is
decided during compilation depending on the number, data type and sequence of actual
parameters. As the issue of polymorphism is resolved at compile time, hence method
overloading is known as COMPILE TIME POLYMORPHISM or STATIC
POLYMORPHISM.
In method overloading, the TYPE of REFERENCE VARIABLE is considered, not the type
of reference.
The following example demonstrates the concept of method overloading.
class Addition
{
void sum(int x, int y)
{
int s=x+y;
[Link] ("The sum is "+s);
}
void sum(int x, double y)
{
double s=x+y;
[Link] ("The sum is "+s);
}
void sum(double x, int y)
{
double s=x+y;
[Link] ("The sum is "+s);
}
int sum(int x, int y, int z)
{
int s=x+y+z;
return s;
}
}
class OverloadMethod
{
public static void main (String s[])
{
int p;
Addition a1=new Addition ();
p=a1. sum (10,20,30); (1)
[Link] ("The sum is "+p);
[Link] (12.5, 18); (2)
[Link] (16, 39); (3)
[Link] (10, 2.5); (4)
}
}
The above example contains four methods called sum (). They are overloaded methods.
Among them return type of three of the methods is void and the return type of the fourth one
is int.
1) The sum () method with three integer parameters has been called.
2) The sum () method with one double and one integer parameter has been called.
3) The sum () method with two integer parameters has been called.
4) The sum () method with one integer and one double type parameter has been called.