views:

280

answers:

2

So, I am just starting Java and, even though I have looked in some question about it here at stackoverflow.com and elsewhere, haven't been able to find a straightforward answer to 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++?

Thanks.

+7  A: 

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?
Alexander Gessler
I always thought that if we did something like int i = foo() or float f = foo() it would know which one, but if the statement is just the function that it the compiler wouldn't know. I get it know. Thanks.
nunos
@nunos even if it was float f = foo() the compiler wouldn't be able to figure it out because both an int would be valid input for an float. Compare float f = 7; (is 7 a float or int?)
NomeN
@NomeN But your statement suggests that func(int i) and func(float i) would be indistinguishable for the compiler - and we all know this is not true. The real reason is given by Oded (see next answer) - it's about the method's signature. And, btw. 7 is definitely integer while 7.0 or 7f is float ;-)
7.0 is not `float`, it's `double`.
FredOverflow
NomeN
+7  A: 

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.

Oded