Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - why no return type based method overloading?

I know this is not possible but can anyone provide a theory as to why Java chose not to support this? I am asking because I just ran into a situation where I think it would be nice to have.

like image 211
llm Avatar asked Apr 30 '10 12:04

llm


People also ask

Why return type is not in method overloading?

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 we overload based on return type in java?

No, you cannot overload a method based on different return type but same argument type and number in java.

Why is method overloading not possible by changing the return type in java example?

Q) Why Method Overloading is not possible by changing the return type of method only? In java, method overloading is not possible by changing the return type of the method only because of ambiguity.

Why does java not support method overloading?

Java doesn't allow user defined operator overloading because if you allow programmer to do operator overloading they will come up with multiple meanings for same operator which will make the learning curve of any developer hard and things more confusing and messing.


2 Answers

Because you are not required to capture the return value of a method in Java, in which case the compiler can not decide which overload to use. E.g.

boolean doSomething() { ... }  int doSomething() { ... }  doSomething(); // which one to call??? 
like image 193
Péter Török Avatar answered Oct 17 '22 22:10

Péter Török


One interesting aspect about this question is the fact that the Java language forbids overloading methods only by return type. But not the JVM:

Note that there may be more than one matching method in a class because while the Java language forbids a class to declare multiple methods with the same signature but different return types, the Java virtual machine does not. This increased flexibility in the virtual machine can be used to implement various language features. For example, covariant returns can be implemented with bridge methods; the bridge method and the method being overridden would have the same signature but different return types.

From: Class.getMethod(String, Class...)

like image 43
Lukas Eder Avatar answered Oct 17 '22 21:10

Lukas Eder