3.6 Method Overloading
Each method has a signature, which comprises the name of the method plus the types and order of the parameters in the formal parameter list. Several method implementations may have the same name, as long as the method signatures differ. This practice is called method overloading. Because overloaded methods have the same name, their parameter lists must be different.
Rather than inventing new method names, method overloading can be used when the same logical operation requires multiple implementations. The Java SE Platform API makes heavy use of method overloading. For example, the class java.lang.Math contains an overloaded method min(), which returns the minimum of two numeric values.
public static double min(double a, double b)
public static float min(float a, float b)
public static int min(int a, int b)
public static long min(long a, long b)
In the following examples, five implementations of the method methodA are shown:
void methodA(int a, double b) { /* … */ } // (1)
int methodA(int a) { return a; } // (2)
int methodA() { return 1; } // (3)
long methodA(double a, int b) { return b; } // (4)
long methodA(int x, double y) { return x; } // (5) Not OK.
The corresponding signatures of the five methods are as follows:
methodA(int, double) 1′
methodA(int)j 2′: Number of parameters
methodA() 3′: Number of parameters
methodA(double, int) 4′: Order of parameters
methodA(int, double) 5′: Same as 1′
The first four implementations of the method named methodA are overloaded correctly, each time with a different parameter list and, therefore, different signatures. The declaration at (5) has the same signature methodA(int, double) as the declaration at (1), and therefore, is not a valid overloading of this method.
void bake(Cake k) { /* … */ } // (1)
void bake(Pizza p) { /* … */ } // (2)
int halfIt(int a) { return a/2; } // (3)
double halfIt(int a) { return a/2.0; } // (4) Not OK. Same signature.
The method named bake is correctly overloaded at (1) and (2), with two different parameter lists. In the implementation, changing just the return type (as shown at (3) and (4) in the preceding example) is not enough to overload a method and will be flagged as a compile-time error. The parameter list in the declarations must be different.
Only methods declared in the same class and those that are inherited by the class can be overloaded. Overloaded methods should be considered to be individual methods that just happen to have the same name. Methods with the same name are allowed, since methods are identified by their signature. At compile time, the right implementation of an overloaded method is chosen, based on the signature of the method call. Details of method overloading resolution can be found in §5.10, p. 265. Method overloading should not be confused with method overriding (§5.1, p. 196).