Why return type of a method is not considered in method overloading ? Can somebody explain , how compiler checks for overloaded methods ?
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.
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