How does the compiler choose between overloaded methods, and what makes two overloads ambiguous?
The compiler picks the overload by looking at the types of the arguments at the call site. It looks for the one method whose parameters match, and if there is exactly one then that is the one that runs.
public class Main {
public static void main(String[] args) {
Printer p = new Printer();
p.print("hello");
p.print("hello", 3);
}
}
And here is the class with the two overloads.
public class Printer {
public void print(String text) {
System.out.println(text);
}
public void print(String text, int times) {
for (int i = 0; i < times; i++) {
System.out.println(text);
}
}
}
So how does the compiler choose? There are three steps and they happen in this order.
the step what the compiler does
---------------------------- --------------------------------------------
1. the exact match it looks for a method whose parameters
match the arguments with no change
2. a widening change it allows a small type to become a
bigger one, such as an int to a long
3. boxing it allows a primitive to become its
wrapper, such as an int to Integer
And what makes two overloads ambiguous? Two things. The first one is that the call matches both of them equally well, so the compiler cannot choose.
public void send(long value) { }
public void send(Integer value) { }
send(5); // this does not compile, the call matches both
// equally well
The second one is that a null argument matches every reference type, so the compiler cannot choose between them.
public void send(String value) { }
public void send(Integer value) { }
send(null); // this does not compile
And there is a third case that is worth knowing about, and it is about the widening rules. A method that takes a long is a better match for a long argument than a method that takes an int, and the compiler uses that to pick. So the most specific match wins.
the methods the call the one that runs
------------------------------- ---------------- ---------------------
print(long), print(int) print(1) print(int)
print(Object), print(String) print("hi") print(String)
print(String), print(Object) print("hi") print(String)
print(long), print(Integer) print(1) print(long)
And there is one more thing about the rules that is worth knowing about, and it is about varargs. A method that takes a variable number of arguments is the last choice, so it is only used when no other method matches.
So the rule to remember is this. The exact match wins, then the widening one, and if two match the same then it is an error.
The next two questions in this topic are about when overloading is a good idea and about the danger of adding one.