Method Overloading in Java


Method overloading in java, same name function/method but different numbers of parameters, different types of parameters, different kinds of parameters.

Rules of Method overloading

  1. Same class.
  2. Same name functions
  3. Different types of parameters
  4. Different numbers of parameters
  5. Different kinds of parameters

Different Numbers of parameters allows the method overloading

Program
public class Main 
{
  public void Show(int a)
  {
    System.out.println("One integer number");
  }
  public void Show(int a,int b)
  {
   System.out.println("Two integer number");
  }
  public static void main(String[] args) 
  {
    Main m1=new Main();
    m1.Show(1);  //calling Show() with one parameter
    m1.Show(1,2);  //calling Show() with one parameter
  }
}

Different types of parameters allows the method overloading

Program
public class Main 
{
  public void Show(int a)
  {
    System.out.println("Integer number = "+a);
  }
  public void Show(float a)
  {
   System.out.println("Float number = "+a);
  }
  public void Show(char a)
  {
   System.out.println("Character = "+a);
  }
  public void Show(String a)
  {
   System.out.println("String = "+a);
  }
  public void Show(boolean a)
  {
   System.out.println("Boolean = "+a);
  }
  public static void main(String[] args) 
  {
    Main m1=new Main();
    m1.Show(1);  //calling Show() integer number
    m1.Show('a'); //calling Show() character
    m1.Show(10.21F); //calling Show() float number
    m1.Show("Hello"); //calling Show() String 
    m1.Show(true); //calling Show() boolean
  }
}


Different kinds of parameters allows the method overloading

Program
public class Main 
{
  public void Show(int ...arg)
  {
   int s=0;
   for(int i: arg)
   s+=i;
   System.out.println("Sum = "+s);
  }
  public void Show(int a,int b)
  {
   int s=a+b;
   System.out.println("Sum = "+s);
  }
  public static void main(String[] args) 
  {
    Main m1=new Main();
    m1.Show(1,2,3,4,5,6); //calling Show() vararg
    m1.Show(1,2); //calling Show() two integer
  }
}

Function overloading is not based on return type only

In Java method we can use variable arguments or arrays of parameters when the size of the parameter list is large. But keep in mind that the parameter array or variable argument must be the last parameter in the parameter list.

Program
public class Main 
{
  public int Show(int a,int b)
  {
   int s=a+b;
   return s;
  }
  public float Show(int a,int b)
  {
   float s=a+b;
   return s;
  }
  public static void main(String[] args) 
  {
    Main m1=new Main();
    System.out.println("Sum(int) = "+m1.Show(1,2));
    System.out.println("Sum(float) = "+m1.Show(1,4)); 
  }
}