您正在使用哪个Java版本?在1.6.0_11中,代码(粘贴在下面)可以编译并运行。
我敢肯定,为什么
foo(testVal)会这样
foo(Object)。
为什么原因
foo(null)去
foo(String)有点复杂。该常量
null是type
nulltype,它是所有类型的子类型。因此,这
nulltype扩展了
String,扩展了
Object。
调用时,
foo(null)编译器将查找具有最特定类型的重载方法。因为
String更具体
Object,所以这就是被调用的方法。
如果您有另一个与String一样特定的重载,
foo(Integer)那么您将得到一个模棱两可的重载错误。
class NullType { public static final void main(final String[] args) { foo(); } static void foo() { Object testVal = null; foo(testVal); // dispatched to foo(Object) foo(null); // compilation problem -> "The method foo(String) is ambiguous" } public static void foo(String arg) { // More-specific System.out.println("foo(String)"); } public static void foo(Object arg) { // Generic System.out.println("foo(Object)"); }}


