开发者

SCJP question: Method ambiguous

开发者 https://www.devze.com 2022-12-22 08:36 出处:网络
Take a look at this code: public class Test { public static void main(String... args) { 开发者_C百科flipFlop(\"hello\", new Integer(4), 2004);

Take a look at this code:

public class Test {
public static void main(String... args) {
  开发者_C百科  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?


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


flipFlop("hello", new Integer(4), 2004); is incompatible with flipFlop(String str, int i, Integer iRef)


Java 5 and later do auto-boxing (convert Integer to int) hence the result.


yes, acc to ques, invocation should depend on difference between int / Integer @ 3rd argument. but here even the difference @ 3rd argument does matter if 2nd arg is autoUnboxed.

even this does work: flipFlop("hex", new Integer(4), new Integer(17));

while acc to syntex and auto box feature, this should call :: "private static void flipFlop(String str, int i, Integer iRef) " method, but all it saying is AMBIGUOUS .....??

0

精彩评论

暂无评论...
验证码 换一张
取 消