Why does the compiler prefer an int overload to a varargs char overload for a char?

前端 未结 4 1175
清酒与你
清酒与你 2020-12-01 07:00

Code

public class TestOverload {

    public TestOverload(int i){System.out.println(\"Int\");}
    public TestOverload(char... c){System.out.println(\"char\"         


        
4条回答
  •  被撕碎了的回忆
    2020-12-01 07:51

    Yes, it is expected behaviour. The precedence for method calling goes like this :

    1. Widending
    2. Boxing
    3. Varargs

    Below is excerpt from Java docs related to same :-

    The process of determining applicability begins by determining the potentially applicable methods (§15.12.2.1).

    The remainder of the process is split into three phases, to ensure compatibility with versions of the Java programming language prior to Java SE 5.0. The phases are:

    The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

    This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.

    The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

    This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method invocation.

    The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.

提交回复
热议问题