Method Overloading


Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters or both.

Sum.java (method overloading)

 // Demonstration of the method overloading 
 public class Sum {
   // Driver code
   public static void main( String args[ ] ) {
     Sum s = new Sum( );
     if ( args.length == 3 )
       System.out.println( s.sum( Integer.parseInt( args[0] ),
                                  Integer.parseInt( args[1] ),
                                  Integer.parseInt( args[2] ) ) );
     else if ( args.length == 2 )
       // See whether the number is a double by checking
       // whether it contains a period.
       if ( args[0].(".") || args[1].(".") )
         System.out.println( s.sum( Double.parseDouble( args[0] ), 
                                    Double.parseDouble( args[1] ) ) );
       else
         System.out.println( s.sum( Integer.parseInt( args[0] ),
                                    Integer.parseInt( args[1] ) ) );
     else
       System.out.println( "Error" );
   }

   // Overloaded sum, which takes two int parameters
   public int sum( int x, int y ) { return x + y; } 

   // Overloaded sum, which takes three int parameters 
   public int sum( int x, int y, int z ) { return x + y + z; } 

   // Overloaded sum, which takes two double parameters 
   public double sum( double x, double y ) { return x + y; } 
 }
shell> java Sum      

Output:             Result:




      “I don’t want to achieve immortality through my work.    
      I want to achieve it by not dying.”    
      — Woody Allen