Why is it not possible to overload a function just by changing the return type? Will that change in a future version of Java?
By the way, just for reference, is this possible in C++?
Why is it not possible to overload a function just by changing the return type? Will that change in a future version of Java?
By the way, just for reference, is this possible in C++?
The reason is that overloads in Java are only allowed for methods with different signatures.
The return type is not part of the method signature, hence cannot be used to distinguish overloads.
See Defining Methods from the Java tutorials.
Return type does not matter while overloading a method. We just need to ensure there is no ambiguity!
The only way Java can know which method to call is by differentiating the types of the argument list. If the compiler allowed two methods with the same name and same argument types, there would be no way to determine which one it should call.
Overloaded
methods in java may have different return types given that the argument is also different.Check out the sample code.
Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
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.
no not really possible that way you can only overload by no of arguments or data type of the arguments