ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-28 12:14:20  阅读:227  来源: 互联网

标签:overloading variadic-functions java


请参见下面的代码:

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有