Why isn't possible to overload a function just by changing the return type? Why is it so? Will that provably change in a future version of Java?
By the way, just for reference, is this possible in C++?
Why isn't possible to overload a function just by changing the return type? Why is it so? Will that provably change in a future version of Java?
By the way, just for reference, is this possible in C++?
You can't do it in Java, and you can't do it in C++. The rationale is that the return value alone is not sufficient for the compiler to figure out which function to call:
public int foo() {...}
public float foo() {..}
...
foo(); // which one?
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 caot be used to distinguish overloads.
See Defining Methods from the Java tutorials.
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 caot declare two methods with the same signature even if they have a different return type.
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.
برچسب: how to deal with stress,how to deal with anger,how to deal with anxiety,how to deal with depression,how to deal with a narcissist,how to deal,how to deal with difficult people,how to deal with a break up,how to deal with rejection,how to deal with jealousy,
نویسنده: استخدام کار