Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the return type not considered when differentiating methods? [duplicate]

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?

like image 223
Silent Warrior Avatar asked Jun 16 '10 17:06

Silent Warrior


People also ask

Why return type is not a part of method signature?

The modifiers, return type, parameter names, and exception list cannot differentiate between overloaded methods and, thus, are not part of the signature.

Why return type is not considered in method overloading in Java?

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.

Why return value is not considered as function overloading criteria?

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.

Can return type be different in method overloading in Java?

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.


2 Answers

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.

like image 122
BalusC Avatar answered Oct 14 '22 08:10

BalusC


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.

like image 26
luke Avatar answered Oct 14 '22 08:10

luke