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?
The modifiers, return type, parameter names, and exception list cannot differentiate between overloaded methods and, thus, are not part of the signature.
The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.
The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded. Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time error as function overloading is not possible here.
Method overloading cannot be done by changing the return type of methods. The most important rule of method overloading is that two overloaded methods must have different parameters.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With