Method Signature
A method signature is essentially the identity of a method. It uniquely identifies a method within a class. A class may contain multiple methods with the same name, but it cannot contain more than one method with the same signature.
When you call a method, you are telling the compiler exactly which method to invoke by referencing its signature. If multiple methods share the same signature, the compiler cannot determine which one to call and will raise an error.
So, what exactly makes up a method signature? Simple: the method name and its ordered list of parameter types. Nothing else contributes to the signature.
For example, all of the following method declarations have the same signature:
void process(int a, String str);
public void process(int value, String name);
void process(int a, String str) throws Exception;
String process(int a, String str);
private int process(int a, String data);
static void process(int a, String str);
In all of these cases, the method name (process) and the ordered parameter types (int, String) are identical.
Their access types, static/instance types, return types, parameter names, and the throws clauses are all different. However, since these attributes are not part of the method signature, they do not make the methods different. The compiler will consider all of the above methods as having the same signature and will complain if you have any two of the above methods in the same class.
Method Overloading
A class cannot have more than one method with the same signature, but it can have multiple methods with the same name and different parameter types. This is known as method overloading. Different parameter types mean different signatures.
From the compiler’s perspective, overloaded methods are simply different methods. It does not matter whether they differ by name, parameter types, or both—only the signature matters.
For example, you can use the same method name println to print an int, a String, or many other types
because the PrintStream class contains multiple overloaded println methods.
Imagine if you had to call printlnByte, printlnShort, printlnString, etc.—method overloading saves you from that frustration.
Ambiguous Overloading Example
Consider the following code:
public class TestClass {
static void doSomething(Integer i, short s) {
System.out.println("1");
}
static void doSomething(int in, Short s) {
System.out.println("1");
}
public static void main(String[] args) {
int b = 10;
short x = 20;
doSomething(b, x);
}
}
This code will not compile. The issue is not the presence of two doSomething methods—they have different signatures, so that part is valid.
The problem lies in the call doSomething(b, x). The compiler cannot determine which overloaded method to use because
both methods are equally applicable after considering autoboxing and type conversions.
Since the compiler cannot choose one unambiguously, it reports an error.
No comments:
Post a Comment