문제

Suppose I have the following two method declarations

public void foo() {/* do something */ }
public void foo(String...args) {/* do something else */}

Then when I invoke foo(), how does Java know that I meant to call the first one? As far as I understand, I could have meant the second. Because the following works just fine.

public void bar(String...args) {}
public void callBar()
{
    // call bar() with no arguments. 
     bar();
}
도움이 되었습니까?

해결책

According to the JLS, the constructor with variable arguments has lowest priority. If the call can be defined without using the varargs method, it will go for that one.

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.

Where "variable arity" refers to the varargs parameter. More info can be found here.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top