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.
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.
No, you cannot overload a method based on different return type but same argument type and number in java.
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.
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.
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???
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...)
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