15 Sept 2012

Return type does not matter in method overloading, why ?

In Java Specs 
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

Start with a example following is a definitions of overloaded get() method.
           int get(int x){
                               return x;
            }

         String get(String str){
                          return str;
          }

when resolving overloaded method calls compiler cares about only formal method argument passed in method call. So a valid call would be
                String str = get("java");
                 int i=get(4);

So now lets back get to the question of return type. Lets say compiler allows to overload the methods on the basis of return type, now formal arguments does not matter. Lets change the method definition.

         int get(){
                      return x;
              }

        String get()
              return str;
           }

when get() method is called compiler slap you with a error. Compiler get confused when finds two methods with a same name.
Java Specs says
Two methods have same signature if they have same name and argument types
Overloading on the basis of return type will not work since compiler does not count the return type for resolving overloading method. Although language like Perl and Haskell do overload methods on return type but Java forget about it.

Please share your view in comments.
 I hope you will return to my blog to read more in-depth posts on java.