Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCJP question: Method ambiguous

Tags:

java

scjp

Take a look at this code:

public class Test {
public static void main(String... args) {
    flipFlop("hello", new Integer(4), 2004);
    // flipFlop("hello", 10, 2004); // this works!
}

private static void flipFlop(String str, int i, Integer iRef) {
    System.out.println(str + " (String, int, Integer)");
}

private static void flipFlop(String str, int i, int j) {
    System.out.println(str + " (String, int, int)");
}

}

The compiler gives an error that the invocation is ambiguous:

Description Resource Path Location Type The method flipFlop(String, int, Integer) is ambiguous for the type Test Test.java scjp19 - inheritence/src line 3 Java Problem

But if the commented-out line is used ti invoke flip-flop, the method is unambiguously invoked (the second one, because autoboxing comes after using the primitive itself).

I would expect the compiler to see that the second argument will be unboxed one way or the other, and judge what method must be invoked depending on the third argument. Why does not this happen? What is the rationale?

like image 236
Markos Fragkakis Avatar asked Apr 13 '26 07:04

Markos Fragkakis


1 Answers

Commented line matches flipFlop(String str, int i, int j) exactly. The other line matches both because of autoboxing.

like image 57
fastcodejava Avatar answered Apr 14 '26 21:04

fastcodejava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!