Method Overloading (Cont.)


Advantages of Method Overloading
We don’t have to create and remember different names for functions doing the same thing. For example, if overloading was not supported, method names like sum1, sum2Int, etc. have to be created in the previous code.

Different Ways to Overload the Method
There are two ways to overload the method: We cannot overload by return type. This behavior is same in C++.

ReturnType1.java (overloading the return type)
public class ReturnType1 {
  public static void main( String args[ ] ) {
    ReturnType1 r = new ReturnType1( );
    System.out.println( r.foo( ) );
  }
  public int  foo( ) { return 10;  } 
  public char foo( ) { return 'a'; } 
}
shell> java ReturnType1

Output:           Result:

However, overloading methods on return type are possible in cases where the data type of the function being called is explicitly specified. For the following example, the command foo('x') will call the method foo with a char input parameter:

ReturnType2.java (overloading the return type)
public class ReturnType2 {
  public static void main( String args[ ] ) {
    System.out.println( foo( 'x' ) );
  }
  public static int  foo( int  a ) { return a; } 
  public static char foo( char a ) { return a; } 
}
shell> java ReturnType2

Output:           Result: