Why is the return type of method not included in the method-signature?

This is done because the compiler would not be able to figure out the overload in all contexts.

For example, if you call

String x = method1("aaa");

the compiler knows that you are looking for the second overload. However, if you call

method1("aaa");

like this, the compiler has no idea which one of the two methods you wanted to invoke, because it is OK to call a method returning String and discard the result. To avoid ambiguities like this, Java prohibits overloads that differ solely on the return type.


You can't overload a method only on it's return type. It's simply illegal. Let's assume for a moment that overloading methods using return type would be legal and you defined two method1 methods. Now we want to call that which returns the String object:

String string = method1(sth);

The JVM theoretically would be able to recognize which method you inteded to call, but what about such call:

method1(sth);

As you can see both methods could be invoked and such operations is unambiguous. The JVM doesn't know which method it should call. This is why such overloading is forbidden.


Since your question doesn't address any particular programming language in the title (I know it does in the tag) I'll share my recent experience with Swift. In Swift function/method signature actually includes return type. So compiler throws an error only if you call this function/method without explicitly specifying return type, e.g.:

func some() -> Bool {
    return true;
}

func some() -> Int {
    return 1;
}

let valBool: Bool = some()
let valInt: Int = some()

// this doesn't work: Ambiguous use of 'some'
some()

On top of this Swift even makes it more interesting. It allows you to have 2 functions/methods with the same parameters and return types only if parameters names are different, e.g.:

func some(#foo: Bool) -> Bool {
    return foo;
}

func some(#bar: Bool) -> Bool {
    return bar;
}

some(foo: true)
some(bar: false)

Thus it gives you semantic differentiation in methods signature

UPD. Since Swift 2.0 external parameter name was changed and now you have to provide external and local names twice even if it's the same

func some(foo foo: Bool) -> Bool {
    return foo;
}

func some(bar bar: Bool) -> Bool {
    return bar;
}

some(foo: true)
some(bar: false)

Tags:

Java