What is method overloading in Java, and what rules does the compiler use to choose between the overloads?
Overloading means giving one name to several methods that differ in their parameters. When you call the name, the compiler looks at the types of the arguments and works out which version you meant.
public class Main {
public static void main(String[] args) {
System.out.println(describe(42)); // the int version
System.out.println(describe(42L)); // the long version
System.out.println(describe(42.5)); // the double version
System.out.println(describe("hello")); // the String version
System.out.println(describe(42, 7)); // the two argument version
}
static String describe(int value) {
return "an int: " + value;
}
static String describe(long value) {
return "a long: " + value;
}
static String describe(double value) {
return "a double: " + value;
}
static String describe(String value) {
return "some text: " + value;
}
static String describe(int first, int second) {
return "two ints: " + (first + second);
}
}
The compiler uses two rules, and they are worth knowing exactly.
The first rule is that the number of arguments has to match. The compiler looks for a version that takes the same number of arguments that you gave it.
The second rule is that the types have to fit without needing a conversion that could lose information. A plain int argument picks the int version, and a long argument picks the long version. A narrow type is widened when it has to be, so an int argument can go to a version that takes a long. But the compiler never does the opposite, because that would lose information.
If no version matches, or if more than one version matches equally well, the compiler reports an error rather than guessing.
So when is overloading a good idea? It is a good idea when several operations are the same idea with different types, such as adding two numbers or printing any value. It is a bad idea when the versions do different amounts of work, because then the name stops describing what the method does.
The next question in this topic looks at the rules that you cannot overload.