خرید بک لینک

Vote count: 45

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++?

asked Mar 13 '10 at 19:49

5 Answers

Vote count: 69 accepted

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?

answered Mar 13 '10 at 19:51

Vote count: 26

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.

answered Mar 13 '10 at 19:53
Oded

Vote count: 15

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.

answered Jan 19 '13 at 16:54

Vote count: 0

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.

answered Jul 23 '13 at 6:38

Vote count: -1

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.

answered Jul 18 at 9:39

برچسب: 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, نویسنده: استخدام کار تاريخ: جمعه 29 مرداد 1395 ساعت: 5:33

صفحه بندی