Method Overloading


When a class has two or more methods by the same name but different parameters, it is known as method overloading. It is different from overriding. In overriding, a method has the same method name, type, number of parameters, etc. Let’s consider an example for finding the maximum number of a list of integers or doubles. Then the concept of overloading will be introduced to create two or more methods with the same name but different parameters:

Overloading.java (method overloading)
public class Overloading {
  public static void main( String[ ] args ) {

    if ( isInteger( args[0] ) ) {
      int result1 = 0;
      for ( int i=0; i < args.length; i++ )
        result1 = maxFunction( result1, Integer.parseInt( args[i] ) );
      System.out.println( "Maximum Value is " + result1 );
    }
    else {
      double result2 = 0.0;
      for ( int i=0; i < args.length; i++ )
        // Same function name with different parameters
        result2 = maxFunction( result2, Double.parseDouble( args[i] ) );
      System.out.println( "Maximum Value is " + result2 );
    }
  }
  public static boolean isInteger( String s ) {
    boolean isValidInteger = false;
    try {
      Integer.parseInt( s );
      // s is a valid integer
      isValidInteger = true;
    }
    catch ( NumberFormatException ex ) {
      // s is not an integer
    }
    return isValidInteger;
  }
  // for integer
  public static int maxFunction( int n1, int n2 ) {
    int max;
    if ( n1 > n2 )  max = n1;
    else            max = n2;
    return max;
  }
  // for double
  public static double maxFunction( double n1, double n2 ) {
    double max;
    if ( n1 > n2 )  max = n1;
    else            max = n2;
    return max;
  }
}
shell> java Overloading (number≥0)        




      “Knowledge speaks, but wisdom listens”    
      ― Jimi Hendrix