If a class have multiple methods by the same name but different parameters it is known as method overloading.

If we have to perform only one operation, having the same name of the methods increases the readability of the program. Highlighted one is the advantage of the method overloading.

The different way to overload the method:

  • By changing number of arguments
  • by changing the data type
Example of method overloading by changing the number of arguments:
class Calculation
{
    void sum(int a,int b){System.out.println(a+b);
}
void sum(int a,int b,int c)
{
    System.out.println(a+b+c);
}
public static void main(String args[])
{
    Calculation obj=new Calculation();
    obj.sum(10,10,10);
    obj.sum(20,20);
}

Output:

30 

40 

  Modified On Feb-25-2018 11:22:03 PM
    1. class Calculation2{  
    1.   void sum(int a,int b){System.out.println(a+b);}  
    1.   void sum(double a,double b){System.out.println(a+b);}  
    1.   
    1.   public static void main(String args[]){  
    1.   Calculation2 obj=new Calculation2();  
    1.   obj.sum(10.5,10.5);  
    1.   obj.sum(20,20);  
    1.   
    1.   }  
    1. }  

    Output:21.0
    40

    Now, question arising why method overloading is not possible by changing the return type of method


    class Calculation3{  
      int sum(int a,int b){System.out.println(a+b);}  
      double sum(int a,int b){System.out.println(a+b);}    
      public static void main(String args[]){  
      Calculation3 obj=new Calculation3();  
      int result=obj.sum(20,20); //Compile Time Error    
      }  
    }  

    int result=obj.sum(20,20); //Here how can java determine which sum() method should be called.

    Can we overload main() method?

    Yes, by method overloading. You can have any number of main methods in a class by method overloading.

    Let's see the simple example:


    class Overloading1{  
    
      public static void main(int a){
      System.out.println(a);
      }

      public static void main(String args[]){
      System.out.println("main() method invoked");
      main(10);
      }
    }  


    Output:main() method invoked

           10




Leave Comment