Method Overloading In Java

  • Post author:
  • Post category:Java
  • Post comments:0 Comments

If a class has multiple methods with the same name but different in parameters is called method overloading.  

  1. By changing the number of arguments: 
class MOL
{  
static int add(int a,int b)
{
return a+b;
}  
static int add(int a,int b,int c)
{
return a+b+c;
}  
}  
class Overloading
{  
public static void main(String[] args)
{  
System.out.println(MOL.add(10,10));  
System.out.println(MOL.add(10,10,10));  
}
}  
Output:
20
30

       2. By changing the data type:

class MOL2
{  
static int add(int a, int b)
{
return a+b;
}  
static double add(double a, double b)
{
return a+b;
}  
}
class Overloading
{  
public static void main(String[] args)
{  
System.out.println(MOL2.add(11,11));  
System.out.println(MOL2.add(1.5,1.5));  
}
}
Output:
22
3.0
  
  

 

Leave a Reply