1. Overview
The method signature is only a subset of the entire method definition in Java. Thus, the exact anatomy of the signature may cause confusion.
In this tutorial, we'll learn the elements of the method signature and its implications in Java programming.
2. Method Signature
Methods in Java support overloading, meaning that multiple methods with the same name can be defined in the same class or hierarchy of classes. Hence, the compiler must be able to statically bind the method the client code refers to. For this reason, the method signature uniquely identifies each method.
According to Oracle, the method signature is comprised of the name and parameter types. Therefore, all the other elements of the method's declaration, such as modifiers, return type, parameter names, exception list, and body are not part of the signature.
Let's take a closer look at method overloading and how it relates to method signatures.
3. Overloading Errors
Let's consider the following code:
public void print() {
System.out.println("Signature is: print()");
}
public void print(int parameter) {
System.out.println("Signature is: print(int)");
}
As we can see, the code compiles as the methods have different parameter type lists. In effect, the compiler can deterministically bind any call to one or the other.
Now let's test if it's legal to overload by adding the following method:
public int print() {
System.out.println("Signature is: print()");
return 0;
}
When we compile, we get a “method is already defined in class” error. That proves the method return type is not part of the method signature.
Let's try the same with modifiers:
private final void print() {
System.out.println("Signature is: print()");
}
We still see the same “method is already defined in class” error. Therefore, the method signature is not dependent on modifiers.
Overloading by changing thrown exceptions can be tested by adding:
public void print() throws IllegalStateException {
System.out.println("Signature is: print()");
throw new IllegalStateException();
}
Again we see the “method is already defined in class” error, indicating the throw declaration cannot be part of the signature.
The last thing we can test is whether changing the parameter names allow overloading. Let's add the following method:
public void print(int anotherParameter) {
System.out.println("Signature is: print(int)");
}
As expected, we get the same compilation error. This means that parameter names don't influence the method signature.
3. Generics and Type Erasure
With generic parameters, type erasure changes the effective signature. In effect, it may cause a collision with another method that uses the upper bound of the generic type instead of the generic token.
Let's consider the following code:
public class OverloadingErrors<T extends Serializable> {
public void printElement(T t) {
System.out.println("Signature is: printElement(T)");
}
public void printElement(Serializable o) {
System.out.println("Signature is: printElement(Serializable)");
}
}
Even though the signatures appear different, the compiler cannot statically bind the correct method after type erasure.
We can see the compiler replacing T with the upper bound, Serializable, due to type erasure. Thus, it clashes with the method explicitly using Serializable.
We would see the same result with the base type Object when the generic type has no bound.
4. Parameter Lists and Polymorphism
The method signature takes into account the exact types. That means we can overload a method whose parameter type is a subclass or superclass.
However, we must pay special attention as static binding will attempt to match using polymorphism, auto-boxing, and type promotion.
Let's take a look at the following code:
public Number sum(Integer term1, Integer term2) {
System.out.println("Adding integers");
return term1 + term2;
}
public Number sum(Number term1, Number term2) {
System.out.println("Adding numbers");
return term1.doubleValue() + term2.doubleValue();
}
public Number sum(Object term1, Object term2) {
System.out.println("Adding objects");
return term1.hashCode() + term2.hashCode();
}
The code above is perfectly legal and will compile. Confusion may arise when calling these methods as we not only need to know the exact method signature we are calling but also how Java statically binds based on the actual values.
Let's explore a few method calls that end up bound to sum(Integer, Integer):
StaticBinding obj = new StaticBinding();
obj.sum(Integer.valueOf(2), Integer.valueOf(3));
obj.sum(2, 3);
obj.sum(2, 0x1);
For the first call, we have the exact parameter types Integer, Integer. On the second call, Java will auto-box int to Integer for us. Lastly, Java will transform the byte value 0x1 to int by means of type promotion and then auto-box it to Integer.
Similarly, we have the following calls that bind to sum(Number, Number):
obj.sum(2.0d, 3.0d);
obj.sum(Float.valueOf(2), Float.valueOf(3));
On the first call, we have double values that get auto-boxed to Double. And then, by means of polymorphism, Double matches Number. Identically, Float matches Number for the second call.
Let's observe the fact that both Float and Double inherit from Number and Object. However, the default binding is to Number. This is due to the fact that Java will automatically match to the nearest super-types that match a method signature.
Now let's consider the following method call:
obj.sum(2, "John");
In this example, we have an int to Integer auto-box for the first parameter. However, there is no sum(Integer, String) overload for this method name. Consequentially, Java will run through all the parameter super-types to cast from the nearest parent to Object until it finds a match. In this case, it binds to sum(Object, Object).
To change the default binding, we can use explicit parameter casting as follows:
obj.sum((Object) 2, (Object) 3);
obj.sum((Number) 2, (Number) 3);
5. Vararg Parameters
Now let's turn our attention over to how varargs impact the method's effective signature and static binding.
Here we have an overloaded method using varargs:
public Number sum(Object term1, Object term2) {
System.out.println("Adding objects");
return term1.hashCode() + term2.hashCode();
}
public Number sum(Object term1, Object... term2) {
System.out.println("Adding variable arguments: " + term2.length);
int result = term1.hashCode();
for (Object o : term2) {
result += o.hashCode();
}
return result;
}
So what are the effective signatures of the methods? We've already seen that sum(Object, Object) is the signature for the first. Variable arguments are essentially arrays, so the effective signature for the second after compilation is sum(Object, Object[]).
A tricky question is how can we choose the method binding when we have just two parameters?
Let's consider the following calls:
obj.sum(new Object(), new Object());
obj.sum(new Object(), new Object(), new Object());
obj.sum(new Object(), new Object[]{new Object()});
Obviously, the first call will bind to sum(Object, Object) and the second to sum(Object, Object[]). To force Java to call the second method with two objects, we must wrap it in an array as in the third call.
The last thing to note here is that declaring the following method will clash with the vararg version:
public Number sum(Object term1, Object[] term2) {
// ...
}
6. Conclusion
In this tutorial, we learned that method signatures are comprised of the name and the parameter types' list. The modifiers, return type, parameter names, and exception list cannot differentiate between overloaded methods and, thus, are not part of the signature.
We've also looked at how type erasure and varargs hide the effective method signature and how we can override Java's static method binding.
As usual, all the code samples shown in this article are available over on GitHub.
The post Does a Method's Signature Include the Return Type in Java? first appeared on Baeldung.