In
Java, it is possible to define two or more methods within the same class that
share the same name, as long as parameter declarations are different. Such
methods are said to be overloaded,
and the process is referred to as method
overloading.
Method
overloading is one of the ways that Java supports polymorphism.
When
Overloaded method is invoked, Java uses type and/or number of arguments to
decide which particular overloaded method to call.
Return
type of the methods are insufficient to distinguish two versions of the method.
Ex:class
Myclass
{
int
a;
void
getdata(int x)
{
a=x;
}
void
display()
{
System.out.println("Value
of A : "+a);
}
int
sum(int x)
{
System.out.println("Method
with one integer is called");
return(a+x);
}
double sum(double x)
{
System.out.println("Method with one double is called");
return(a+x);
}
int sum(int x,int y)
{
System.out.println("Method with two integers is called");
return(a+x+y);
}
}
class Overload
{
public
static void main(String args[])
{
Myclass
c=new Myclass();
c.getdata(10);
int x=c.sum(20);
double y=c.sum(10.50);
int z=c.sum(5,6);
System.out.print("\nX :
"+x+" Y : "+y+" Z : "+z);
}
}
Output:Method
with one integer is called
Method
with one double is called
Method
with two integers is called
X : 30
Y : 20.5 Z : 21
No comments:
Write comments