Distinguishing overloaded methods
If the methods have the same name, how can Java know which method you mean? There’s a simple rule: each overloaded method must take a unique list of argument types.
If you think about this for a second, it makes sense. How else could a programmer tell the difference between two methods that have the same name, other than by the types of their arguments?
Even differences in the ordering of arguments are sufficient to distinguish two methods: (Although you don’t normally want to take this approach, as it produces difficult-to-maintain code.)
//: c04:OverloadingOrder.java
// Overloading based on the order of the arguments.
import com.bruceeckel.simpletest.*;
public class OverloadingOrder {
static Test monitor = new Test();
static void print(String s, int i) {
System.out.println("String: " + s + ", int: " + i);
}
static void print(int i, String s) {
System.out.println("int: " + i + ", String: " + s);
}
public static void main(String[] args) {
print("String first", 11);
print(99, "Int first");
monitor.expect(new String[] {
"String: String first, int: 11",
"int: 99, String: Int first"
});
}
} ///:~
The two print( ) methods have identical arguments, but the order is different, and that’s what makes them distinct.