Java Reference
In-Depth Information
If you call
max
with
int
parameters, the
max
method that expects
int
parameters will be
invoked; if you call
max
with
double
parameters, the
max
method that expects
double
para-
meters will be invoked. This is referred to as
method overloading
; that is, two methods have
the same name but different parameter lists within one class. The Java compiler determines
which method to use based on the method signature.
Listing 5.9 is a program that creates three methods. The first finds the maximum integer,
the second finds the maximum double, and the third finds the maximum among three double
values. All three methods are named
max
.
method overloading
L
ISTING
5.9
TestMethodOverloading.java
1
public class
TestMethodOverloading {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Invoke the max method with int parameters
5 System.out.println(
"The maximum of 3 and 4 is "
6 +
max(
3
,
4
)
);
7
8
// Invoke the max method with the double parameters
9 System.out.println(
"The maximum of 3.0 and 5.4 is "
10 +
max(
3.0
,
5.4
)
);
11
12
// Invoke the max method with three double parameters
13 System.out.println(
"The maximum of 3.0, 5.4, and 10.14 is "
14 +
max(
3.0
,
5.4
,
10.14
)
);
15 }
16
17
/** Return the max of two int values */
18
public static int
max(
int
num1,
int
num2)
{
overloaded
max
19
if
(num1 > num2)
20
return
num1;
21
else
22
return
num2;
23 }
24
25
/** Find the max of two double values */
26
public static double
max(
double
num1,
double
num2)
{
overloaded
max
27
if
(num1 > num2)
28
return
num1;
29
else
30
return
num2;
31 }
32
33
/** Return the max of three double values */
34
public static double
max(
double
num1,
double
num2,
double
num3)
{
overloaded
max
35
return
max(max(num1, num2), num3);
36 }
37 }
The maximum of 3 and 4 is 4
The maximum of 3.0 and 5.4 is 5.4
The maximum of 3.0, 5.4, and 10.14 is 10.14
When calling
max(3, 4)
(line 6), the
max
method for finding the maximum of two integers
is invoked. When calling
max(3.0, 5.4)
(line 10), the
max
method for finding the maxi-
mum of two doubles is invoked. When calling
max(3.0, 5.4, 10.14)
(line 14), the
max
method for finding the maximum of three double values is invoked.