Java Reference
In-Depth Information
Still, the second parameter type does not match; the actual type is short and the formal type is double . Java allows
automatic widening from short to double . The compiler converts the short type to the double type and binds
add(f1, s2) call to add(double, double) method. When ot.test(mgr) is called, the compiler looks for an exact
match and, in this case, it finds one, test(Manager m) , and binds the call to this version of the test() method. Suppose
the test(Manager m) method is not present in the OverloadingTest class. The compiler will bind ot.test(mgr) call to
test(Employee e) method because a Manager type can be widened (using upcasting) to Employee type automatically.
Sometimes, overloaded methods and automatic type widening may confuse the compiler resulting in a compiler
error. Consider Listings 16-16 and 16-17 for an Adder class with an overloaded add() method and how to test it.
Listing 16-16. The Adder Class, Which Has Overloaded add().method
// Adder.java
package com.jdojo.inheritance;
public class Adder {
public double add(int a, double b) {
return a + b;
}
public double add(double a, int b) {
return a + b;
}
}
Listing 16-17. Testing add() Method of the Adder Class
// AdderTest.java
package com.jdojo.inheritance;
public class AdderTest {
public static void main(String[] args) {
Adder a = new Adder();
double d = a.add(2, 3); // A compile-time error
}
}
An attempt to compile the AdderTest class generates the following error:
"AdderTest.java": reference to add is ambiguous, both method add(int,double) in
com.jdojo.inheritance.Adder and method add(double,int) in com.jdojo.inheritance.Adder match at
line 7, column 18
The error message states that compiler is not able to decide which one of the two add() methods in the Adder
class to call for a.add(3, 7) method invocation. The compiler is confused in deciding if it should widen the int type
of 3 to make it double type 3.0 and call the add(double, int) or if it should widen the int type of 7 to make it double
type 7.0 and call the add(int, double). In situations like this, you need to help the compiler by using a typecast
as follows:
double d1 = a.add((double)2, 3); // OK. Will use add(double, int)
double d2 = a.add(2, (double)3); // OK. Will use add(int, double)
 
Search WWH ::




Custom Search