In java we can define more than one method inside one class(same class), whose names are same until their parameters or signature are different. This process or method of having more than one method within same class with different parameters or signature is know as overloading of a method.
Overloading is needed when we want our objects to perform same work but by using different parameters.
For doing this process of overloading, you have to simply give more than one method within the same class having same name but contain different parameters.
Syntax
class className
{
// variable declaration
// methods
type1 methodName(parameter1)
{
// statements
}
type2 methodName(parameter2)
{
// statements
}
}
eg:-
class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String a1, String a2)
{
return a1 + a2;
}
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(5,6));
System.out.println(sObj.addition("Hello ", "All"));
System.out.println(sObj.addition(2.5,2));
}
}
Output
11
Hello All
4.5
0 Comment(s)