HOW TO OVERLOAD METHODS IN JAVA:
Method can be simply be overloaded by using one rule.
- Number of input parameter of method should be different from others.As we done in below program.
void input()
void input(int a)
- Parameter data type should be different from others for example if one method takes double so other should not use double data type as a parameter.
EXAMPLE:
void input(double a)
void input(int a)
NOTE:Method can not be overloaded by changing return type of method.
CODING:
class overloading
{
void input()
{
System.out.println("No Parameter");
}
//overload method for one parameter
void input(int a)
{
System.out.println("a="+a);
}
//overload method for two parameter
void input(int a,int b)
{
System.out.println("a = "+a+" b= "+b);
}
//overload method for returning double parameter
double input(double a)
{
System.out.println("Double Value of a="+a);
return a*a;
}
}
class mainoverload
{
public static void main(String arg[])
{
overloading x = new overloading();
//calling all version of input methods
x.input();
x.input(50);
x.input(100,30);
double ans=x.input(123.4567);
System.out.print("Result of x.input(123.4567)="+ans);
}
}
OUTPUT:
No parameter
a = 100 b=30
Double Value of a = 123.4567
Result of x.input(123.4567)=15241.55677489
No comments:
Post a Comment