Sub topic 8
Overload Methods with Different Parameters
A method is a named set of instructions. In Java, you can give several methods the same name if they accept different inputs. This is called method overloading.
Overloading lets you use one name for closely related tasks. For example, a method named label could make a label for one number or for a pair of numbers. The method name tells you the task. The inputs tell Java which version to use.
What makes an overload different?
A parameter is a variable listed in a method’s declaration. An argument is a value supplied when you call the method. A type describes what kind of value a variable can hold. For example, int holds whole numbers, and double holds numbers that can have a fractional part.
Overloaded methods in the same class must have different parameter lists. They can differ in:
- The number of parameters.
- The types of parameters.
- The order of parameter types.
A method’s signature consists of its name and parameter types, in order. For the examples in this chapter, you can read label(int, double) as the name label followed by its two parameter types.
| Signatures | Different overloads? | Reason |
|---|---|---|
| `label(int)` and `label(int, int)` | Yes | They have different numbers of parameters. |
| `label(int)` and `label(double)` | Yes | Their parameter types differ. |
| `show(int, double)` and `show(double, int)` | Yes | Their parameter types are in a different order. |
| `label(int)` and another `label(int)` | No | Their names and parameter types are the same. |
Changing only parameter names does not create an overload. For example, a method with the parameter int first has the same signature as one with int number if both methods have the same name.
Likewise, swapping the names in (int first, int second) does not make a new signature. The types are still int, int.
A worked example
This program defines three methods named label. Each one makes text that describes its inputs.
String is the Java type for text. Each label method has a return type of String, so it sends text back to its caller. The keyword static lets the program call these methods without first creating an object.
Save the following code in a file named LabelDemo.java:
public class LabelDemo {
static String label(int number) {
return "Whole number: " + number;
}
static String label(double number) {
return "Decimal number: " + number;
}
static String label(int first, int second) {
return "Two numbers: " + first + " and " + second;
}
public static void main(String[] args) {
System.out.println(label(7));
System.out.println(label(2.5));
System.out.println(label(3, 5));
System.out.println(label(2.5f));
}
}Compile and run it from the folder that contains the file:
javac LabelDemo.java
java LabelDemoThe program prints these lines, in order:
Whole number: 7Decimal number: 2.5Two numbers: 3 and 5Decimal number: 2.5
Look at the first three calls:
label(7)supplies oneintargument. Java selectslabel(int).label(2.5)supplies onedoubleargument. Java selectslabel(double).label(3, 5)supplies twointarguments. Java selectslabel(int, int).
The fourth call uses a conversion, which we will examine next.
How Java selects an overload
The compiler is the Java tool that checks and translates your code before it runs. For an overloaded call, the compiler uses the number and types of the arguments to find an applicable method.
An applicable method is one that can accept the given arguments. When more than one method can accept them, the compiler applies Java’s rules to choose the most suitable one. If it cannot make a choice, it reports an error.
Exact matches and conversions
In LabelDemo, the argument 7 is an int. Both label(int) and label(double) can accept it: Java can convert an int to a double. However, label(int) is an exact match, so Java selects it.
The argument 2.5 is a double. Java selects label(double).
The argument 2.5f has the type float, another type for numbers with a fractional part. The f at the end marks it as a float. There is no label(float) method, but Java can convert a float to a double for the call. So it selects label(double).
This kind of automatic conversion is called a widening conversion. Not every conversion is allowed automatically. In particular, Java will not automatically convert a double to an int for a method call.
For example, label(3.0, 5) does not work in this program. The only two-parameter version expects two int values, but 3.0 is a double. Use label(3, 5) if you mean to pass two whole numbers.
The type matters, not just the value
A value can look like a whole number and still have type double. For example, 7.0 is a double, so label(7.0) calls label(double).
The same is true for a variable. If you declare double amount = 7;, then label(amount) calls label(double). The compiler uses the declared type of amount, even though its value is a whole number.
Return types do not create overloads
A return type tells Java what type of result a method sends back. Overloaded methods may have different return types, but their parameter lists must still differ.
For example, these two declarations cannot both appear in the same class:
static int count(int number)static double count(int number)
Their return types differ, but both have the signature count(int). Changing number to a different parameter name would not fix the problem.
To make valid overloads, change the parameter list. For example, count(int) and count(int, int) are different signatures.
The static keyword and access words such as public also do not make otherwise identical parameter lists into overloads.
When a call is ambiguous
Sometimes more than one overload can accept a call, but neither is the better choice. This is an ambiguous call. The compiler rejects it rather than guessing.
The next program has two show methods. They have the same parameter types in opposite order. Save it as ChoiceDemo.java:
public class ChoiceDemo {
static void show(int first, double second) {
System.out.println("int first, double second");
}
static void show(double first, int second) {
System.out.println("double first, int second");
}
public static void main(String[] args) {
show(1, 1.0);
show(1.0, 1);
// show(1, 1); // Ambiguous: uncommenting this causes an error.
}
}The return type void means the methods do not send a result back. They print a message instead.
Compile and run the program:
javac ChoiceDemo.java
java ChoiceDemoThe first call selects show(int, double). The second selects show(double, int).
Now consider show(1, 1). Both arguments are int values:
show(int, double)can accept them by converting the second argument todouble.show(double, int)can accept them by converting the first argument todouble.
Neither choice is better for both arguments, so the call is ambiguous. Writing show(1, 1.0) makes the intended choice clear.
Use overloads with care
Overloads are easiest to understand when they do the same kind of job. The label methods all make labels; they differ only in the inputs they accept.
Keep these points in mind:
- Choose one clear name for related actions. Use different names for unrelated actions.
- Make it easy to tell what each overload accepts. Overloads with similar numeric types can make calls harder to predict.
- Check the signature, not just the parameter names or return type, when the compiler reports a duplicate method.
- Read argument types as well as values.
7and7.0can select different methods. - If a call is ambiguous, give the arguments types that clearly select the method you want.
Overloading gives callers a convenient choice, but it should not make them guess what a method does.
Practice
Exercise
A class has print(int value). Which is a valid overload: print(int amount), print(double value), or both?
Show answer
Only print(double value) is a valid overload. Changing value to amount changes a parameter name, not its type.
Exercise
In LabelDemo, which method does label(8.0) call, and why?
Show answer
It calls label(double) because 8.0 has type double.
Exercise
In ChoiceDemo, why is show(2, 2) ambiguous? Rewrite the call to select the method whose first parameter is an int.
Show answer
Each overload can accept the call by converting one argument from int to double, and neither is the better choice. Write show(2, 2.0) to select show(int, double).