views:

113

answers:

2

Why return type of a method is not considered in method overloading ? Can somebody explain , how compiler checks for overloaded methods ?

+8  A: 

Why return type of a method is not considered in method overloading?

The main reason is that if you did consider this, a lot of function calls become ambiguous if the return value is not assigned to something. For example, which function call is being invoked here?

public String x() { ... }
public int x() { ... }

// ...

x();  // <-- Which one did you mean? It's impossible to tell if you
      //     allow return types to be part of method overloads.

There are other reasons to not want to do this, too. That said, many languages do allow their signatures to differ only in return type; Haskell and Perl are two examples. If your language does allow this, it's not hard to see that all you'd need to support this is one more step in your method-resolution process: simply have an obvious way for the compiler to select one method or another. In the example above, perhaps we would define a priority (maybe the first method defined is the one that wins, for example, so our x() call would invoke String x()).

Another thing to note is that the JVM does allow two methods whose signature differs only in return type to exist. (That's how Scala and other JVM languages that support this do it.

John Feminella
Even if you *do* assign it, it can be ambiguous in the case of a class and one of its children.
Ignacio Vazquez-Abrams
A tie-breaker rule for dealing with ambiguous calls can lead to nasty surprises; e.g. if the programmer has not noticed that there is an overload. That's probably why the Java language designers didn't take that approach.
Stephen C
@Stephen C » Right, I didn't say it was a _good_ idea! :) I was just trying to illustrate that there wasn't a fundamental technical issue that prevents this from happening (indeed, there isn't one, because Scala uses the JVM and it has this ability, as I note in my answer).
John Feminella
+2  A: 

Can somebody explain , how compiler checks for overloaded methods ?

The Java Language Specification, section 8.4.9, will contain the definitive (but very technical) answer: http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.9

Will