Java Reference
In-Depth Information
Listing 6.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 .
L ISTING 6.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 maximum
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.
Can you invoke the max method with an int value and a double value, such as max(2,
2.5) ? If so, which of the max methods is invoked? The answer to the first question is yes.
The answer to the second question is that the max method for finding the maximum of two
double values is invoked. The argument value 2 is automatically converted into a double
value and passed to this method.
 
 
Search WWH ::




Custom Search