编程语言
首页 > 编程语言> > java-方法oveloading-对象与对象变量

java-方法oveloading-对象与对象变量

作者:互联网

请参见下面的代码:

// 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
}

我希望第一次调用和第二次调用都应调用第一种方法,以为null会比Object … vararg更匹配Object.但是我错了.

>第一个调用调用了第二个方法
>第二个调用调用了第一个方法

我的问题是为什么或如何将null匹配Object … vararg而不是我的代码中的Object?

解决方法:

JLS 15.12.2解释了这种确切的情况:

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.

标签:overloading,variadic-functions,java
来源: https://codeday.me/bug/20191028/1952284.html