Does the method signature in a Java class/interface include its return type?
Example:
Does Java know the difference between those two methods:
public class Foo { public int myMethod(int param) {} public char myMethod(int param) {} }
Or is it maybe only the method name and parameters list that matter?
In Java programming language, the method signature consists of two parts: the method's name and the parameter list. These two parts are part of a method declaration. The parameter list includes the number, type, and order of parameters but not the name of the parameter.
For functions that are specializations of function templates, the signature includes the return type. For functions that are not specializations, the return type is not part of the signature.
Because it is an attempt to define two methode with same signature. which is being checked in methode table and it is not allowed.
But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible. Java can distinguish the methods with different method signatures.
Quoting from Oracle Docs:
Definition: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.
Since the question was edited to include this example:
public class Foo { public int myMethod(int param) {} public char myMethod(int param) {} }
No, the compiler won't know the difference, as their signature: myMethod(int param)
is the same. The second line:
public char myMethod(int param) {}
will give you can error: method is already defined in class, which further confirms the above statement.
Is class method signature in Java includes return type ?
In Java, it doesn't but in this JVM it does which can lead to obvious confusion.
Is interface method signature in Java includes return type ?
The same as for class methods.
Or only method name and parameters list ?
Method name and parameter types for Java. For example, the parameter annotations and names don't matter.
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