Oveloading - Object vs Object vararg method

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 that 1st call

, and 2nd call

both need to call 1st method

, thinking that null

prefers to compare Object

than Object...

vararg. But I am wrong.

  • 1st call

    invoked 2nd method

  • 2nd call

    invoked 1st method

My question is, why and how does vararg null

match Object...

and not Object

in my code?

+3


source to share


2 answers


JLS 15.12.2 explains this exact scenario:



The first phase (§15.12.2.2) performs overload resolution without boxing permission or conversion for unboxing, or using a method call to the arity variable . If no applicable method is found at this stage, processing continues until the second phase.

This ensures that any calls that were valid in the Java programming language prior to Java SE 5.0 are not considered ambiguous as a result of injecting arity variable methods, implicit boxing, and / or unboxing. However, a method declaration of an arity variable (§8.4.1) may change the method chosen to express a method invocation of that method, because the arity variable method is treated as a fixed arity method in the first phase. For example, declaring m (Object ...) in a class that already declares m (Object) results in m (Object) no longer being selected for some call expressions (such as m (null)) like m (Object [])) more specifically .

+2


source


Since it Object...

is essentially Object[]

, and because it null

is valid Object[]

, it will match the most specific one.

If you have 3 methods with the first parameter Object

, the second has SubClass

param and the last has SubSubClass

param, the latter will be selected.



If you add a method with a parameter String

to the source code, you will get a compile-time error, as there is no longer a special match for null

.

+2


source







All Articles