问题
See the code below:
// 1st method
private static void method(Object o){
System.out.println("object method");
}
// 2nd method
private static void method(Object... o){
System.out.println("object vararg method");
}
public static void main(String [] ar){
method(null); // 1st call
Integer value=null;
method(value); // 2nd call
}
I expected 1st call
and 2nd call
both should invoke 1st method
, thought null
will prefer to match Object
than Object...
vararg. But I am wrong.
1st call
invoked2nd method
2nd call
invoked1st method
My question is why or how null
matches to Object...
vararg and not Object
in my code?
回答1:
JLS 15.12.2 explains this exact scenario:
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.
回答2:
Because Object...
is essentially Object[]
and since null
is a valid Object[]
, it will match to the most specific one.
If you had 3 methods with first having Object
parameter, the second having SubClass
param and the last having SubSubClass
param, the last one would be chosen.
Whereas if you add a method with a String
parameter to your original code, you will get a compile time error, since there is no longer a single most specific match for null
.
来源:https://stackoverflow.com/questions/29847538/method-oveloading-object-vs-object-vararg