Why does return type of method not included in signature?
An example
public void method1(String arg){...} public String method1(String arg){...}
It will cause an error.
Method signature does not include the return type of the method. A class cannot have two methods with same signature.
When a method is called, the corresponding method is invoked by matching the arguments in the call to the parameter lists of the methods. The name together with the number and types of a method's parameter list is called the signature of a method. The return type itself is not part of the signature of a method.
Return type is not part of the method signature in C#. Only the method name and its parameters types (but not the parameter names) are part of the signature.
A method's signature specifies the allowable types of all its arguments and of its return value. The signature of a method consists of the name of the method and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With