Java Reference
In-Depth Information
You may be wondering why the method max(double, double) is not invoked for the
call max(3, 4) . Both max(double, double) and max(int, int) are possible matches
for max(3, 4) . The Java compiler finds the method that best matches a method invocation.
Since the method max(int, int) is a better matches for max(3, 4) than max(double,
double) , max(int, int) is used to invoke max(3, 4) .
Tip
Overloading methods can make programs clearer and more readable. Methods that per-
form the same function with different types of parameters should be given the same
name.
Note
Overloaded methods must have different parameter lists. You cannot overload methods
based on different modifiers or return types.
Note
Sometimes there are two or more possible matches for the invocation of a method, but
the compiler cannot determine the best match. This is referred to as ambiguous invo-
cation. Ambiguous invocation causes a compile error. Consider the following code:
ambiguous invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max( 1 , 2 ));
}
public static double max( int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max( double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Both max(int, double) and max(double, int) are possible candidates to match
max(1, 2) . Because neither is better than the other, the invocation is ambiguous,
resulting in a compile error.
6.15
What is method overloading? Is it permissible to define two methods that have the
same name but different parameter types? Is it permissible to define two methods in a
class that have identical method names and parameter lists but different return value
types or different modifiers?
Check
Point
6.16
What is wrong in the following program?
public class Test {
public static void method( int x) {
}
public static int method( int y) {
 
 
Search WWH ::




Custom Search