Method overloading means when two or more methods have the same name but a different signature. Signature of a method is nothing but a combination of its name ans the sequence of its parameter types. Advantages of method overloading
- It allows you to use the same name for a group of methods that basically have the same purpose.
- It provides an easy way to handle default parameter value.
Assume that a method has one required parameter and two optional parameters. Three overloaded forms of this method can be defined. It can accept one, two or three parameters.
Best example of overloading method is println() method. This method have many overloaded forms where each of these accepts one argument of a different type. The type may be a boolean, char, int, long, flaot, double, String, char[] or Object.
Syntax of Method Overloading
class clsName
{
// variable declaration
// constructor declaration
// methods
rtype1 mthName(cparam1)
{
// body of method
}
rtype2 mthName(cparm2)
{
// body of method
}
}
Example of Method Overloading
Example 1 : Program that illustrates method overloading
class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class AddOperation
{
public static void main(String args[])
{
Sample sObj = new Sample();
System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2));
}
}
Output
3
Hello World
3.5