overloading with both widening and boxing

后端 未结 2 2132
滥情空心
滥情空心 2021-01-05 21:33
public void add(long... x){}
public void add(Integer... x){}

add(2);

this produces error...why overlaoding is not performed with both widening an

2条回答
  •  渐次进展
    2021-01-05 21:54

    Java compiler performs three attempts to choose an appropriate method overload (JLS §15.12.2.1):

    • Phase 1: Identify Matching Arity Methods Applicable by Subtyping
      (possible boxing conversions and methods with varargs are ignored)

    • Phase 2: Identify Matching Arity Methods Applicable by Method Invocation Conversion
      (takes boxing conversion in account, but ignores methods with varargs)

    • Phase 3: Identify Applicable Variable Arity Methods
      (examines all possibilities)

    So, with your examples it works as follows:

    • Without varargs: add(long x) is identified as the only applicable method on the 1st phase (this method is applicable by subtyping since int is a subtype of long, §JLS 4.10.1), so that following phases are not executed.

    • With varargs: overload resoltion algorithm goes to phase 3, where both methods are identified as applicable, and compiler can't choose the most specific method of them (choosing the most specific method is yet another complex algorithm), therefore it reports ambiguity.

    See also:

    • The Java Language Specification, Seventh Edition

提交回复
热议问题