views:

161

answers:

5

Possible Duplicate:
Java - why no return type based method overloading?

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
Java Tutorial

Why is this?

+13  A: 

Because it's not required to assign the result when you want to execute a method. How would the compiler then know which of the overloaded ones you'd like to call? There will be ambiguity.

BalusC
What happens to returned values if they aren't assigned? Do they just get GC'd?
Pierreten
@Pierreten: If not referenced elsewhere (from inside the method on for example), then yes.
BalusC
A: 

Because a calling method would need to pass the return type to the method being called.

So you have

Public Integer doStuff(String thing) { };

and

Public Double doStuff(String thing) { };

The class calling doStuff would need to tell the class to use the doStuff that takes a string (already does), and returns a Double (does not do).

The reason WHY java does this? To help prevent horrible code like I listed above I assume :) Overloading is easy to make a mess with, and I am not sure I see the benefit to the case above.

bwawok
+2  A: 

Because you can't tell from just the method invocation what the return type is supposed to be. The compiler needs to be able to tell, using only information at the call site, what method to call. Return values may be discarded so you can't in general know that there is a return value and what its type is. it gets even more confusing once you start thinking about type coersions (short->int) or casts.

Basically when the compiler sees a method call it knows all of the arguments need to be there in order to be a valid method call, so it can use those arguments to find the right method to call. But returns values will not be known at the time of the call, and even the type of the return value may not be discoverable.

luke
A: 

Any given call site could successfully use a number of different return types, due to polymorphism and auto-(un)boxing at the very least, so this would either need rules to deal with ambiguous cases, or only work in simple circumstances.

pdbartlett
A: 

I just wanted to point out that - while not possible in Java - Ada supports overloading that is based purely on return types. Yet Google's best explaination on how that works is a stack overflow post:

http://stackoverflow.com/questions/442026/function-overloading-by-return-type/442291#442291

nd