Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a method's signature in Java include its return type?

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?

like image 835
faressoft Avatar asked Apr 22 '13 14:04

faressoft


People also ask

What is included in a method's signature Java?

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.

Does function signature include return type?

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.

Why return type is not part of 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.

What happens when the method signature is the same and the return type is different?

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.


2 Answers

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.

enter image description here

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.

like image 154
Jops Avatar answered Oct 01 '22 15:10

Jops


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.

like image 35
Peter Lawrey Avatar answered Oct 01 '22 15:10

Peter Lawrey