使用null的方法重载选择 [英] Method overload selection with null
问题描述
鉴于此代码:
class Overloading
extends Object
{
static public void target(Object val, String chk) { System.out.println("Object["+val+"] :: Should be "+chk); }
static public void target(String val, String chk) { System.out.println("String["+val+"] :: Should be "+chk); }
static public void main(String[] args) {
Object obj=null;
target(null ,"Object");
target((Object)null,"Object");
target(obj ,"Object");
}
}
输出(意外)如下:
String[null] :: Should be Object
Object[null] :: Should be Object
Object[null] :: Should be Object
问题出在第一行,我希望是第一行和其他两个一样。此外,我发誓,直到最近编译器才会给我一个模糊的调用警告,用于普通的 null
调用。然而,使用Java 5和6进行编译和测试会产生相同的结果。
The problem is with the first line, which I expect to be the same as the other two. Furthermore, I would swear that until recently the compiler would give me an ambiguous invocation warning for the plain null
call. However compiling and testing with Java 5 and 6 yields the same results.
这对我来说是个重要问题,因为我有很多代码使用这种模式使用重载不同类型的default参数以选择返回类型并推断所需的转换/解析。任何人都可以解释这里发生了什么吗?
This is a significant issue for me since I have a lot of code which uses this pattern of using an overloaded "default" parameter of different types to select a return type and infer required conversion/parsing. Can anyone explain what is going on here?
推荐答案
Java总是以同样的方式工作:最具体适用的重载是总是选择。由于 String
是 Object
的子类,因此它更具体,而字符串
选择了重载。如果重载是,例如 String
和 Integer
,并且您尝试传递 null
,那么你确实会得到编译时歧义错误,因为它们都处于同一继承层次结构的同一级别。
Java has always worked the same way: the "most specific" applicable overload is always chosen. Since String
is a subclass of Object
, it is "more specific", and the String
overload is chosen. If the overloads were for, say String
and Integer
, and you tried to pass null
, then you would indeed get a compile-time ambiguity error, since they are both at the same level of the same inheritance hierarchy.
这篇关于使用null的方法重载选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!