Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 391
Mary Ryllo Avatar asked Nov 09 '12 19:11

Mary Ryllo


People also ask

Is return type included in method signature?

Method signature does not include the return type of the method. A class cannot have two methods with same signature.

Which is not part of signature of method?

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.

Is return type part of method signature C#?

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.

Does method signature include return type C++?

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.


1 Answers

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.

like image 181
Sergey Kalinichenko Avatar answered Oct 30 '22 03:10

Sergey Kalinichenko