Reputation: 7859
Why is the compiler complaining here?
public static void main(String[] args) {
flipFlop(new Integer(11), 20f);
}
private static void flipFlop(int i, Float iRef) {
}
private static void flipFlop(int i, float j) {
}
But not here?
public static void main(String[] args) {
flipFlop(11, 20f);
}
private static void flipFlop(int i, Float iRef) {
}
private static void flipFlop(int i, float j) {
}
That's strange because it should resolve in both cases.
Only the second parameter could become ambiguous in some cases but not the first. So why is it complaining if I change the first.
Upvotes: 2
Views: 83
Reputation: 2217
Your second example matches the signature of the second flipFlop. The first call matches neither flipFlops, so the compiler attempts to select the most specific match, and both are equally specific because both require boxing/unboxing to match. Since they are equally applicable, the call is ambiguous.
See the Java Language Specification, Clause 15.12 Method Invocation Expressions.
Upvotes: 0
Reputation: 307
In first case you box the value into and Integer,and it is not unboxed when received as is should be and int,the JVM does not do unboxing in case of arguments. In the second case you give a primitive type int to the int argument and the second argument is autoboxed.
Upvotes: 0
Reputation: 328598
When several methods are applicable, the compiler tries to find the most specific one. If two methods are maximally specific, there is an ambiguity and you get an error.
In summary (the actual rules are a little more complicated):
Upvotes: 4
Reputation: 7880
In the second case you have an exact match for the method signature. In the first case it's ambiguous. Do you unbox the Integer
or box the Float
?
Upvotes: 1