Method Overloading
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 and 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 has 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.
Example 1: Program that
illustrates method overloading
class Myclass
{
int addition()
{
return(10);
}
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[])
{
Myclass Obj = new Myclass ();
System.out.println(Obj.addition();
System.out.println(Obj.addition(1,2));
System.out.println(Obj.addition("Hello
","World"));
System.out.println(Obj.addition(1.5,2));
}
}
Output
10
3
Hello World
3.5
1 comments:
ReplyDelete