Method Overloading in Java
In java method overloading means we are using overloading methods.That means if a class have multiple methods by same name but different parameters, it is known as Method Overloading.
If we need to perform one operation and as explained above the method name increases the readability of the program.
Method overloading is a type of polymorphism, called static polymorphism.
Different ways to overload the method
There are two ways to overload the method in java |
|
Example 1: Overloading – Different Number of parameters in argument list
class MethodOverloading
{
public void display(int a)
{
System.out.println(a);
}
public void display(int a, char ch)
{
System.out.println(ch+ " "+a);
}
}
class Sample
{
public static void main(String args[])
{
MethodOverloading abc= new MethodOverloading();
abc.display(5);
abc.display(5,'A');
}
}
Output:5
A 5
2)Example of Method Overloading by changing data type of argument
class MethodOverloading {
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
MethodOverloading abc=new MethodOverloading ();
abc.sum(5.5,5.5);
abc.sum(10,10);
}
}
Output:
11.0
20
No comments :
Post a Comment