为什么直接传递null
参数和传递赋有值null
的Object
参数会产生不同的结果呢?
Object testVal = null;
test.foo(testVal); // dispatched to foo(Object)
// test.foo(null); // compilation problem -> "The method foo(String) is ambiguous"
public void foo(String arg) { // More-specific
System.out.println("foo(String)");
}
public void foo(Object arg) { // Generic
System.out.println("foo(Object)");
}
换句话说,为什么被注释的第二次调用 foo(...)
没有被派发到 foo(Object)
中?更新:我使用的是Java 1.6。我可以编译Hemal的代码,但我的代码仍然不能编译。我唯一看到的区别是Hemal的方法是静态的,而我的方法不是。但我真的不知道为什么这会有任何影响...?
更新2:问题已解决。我在类中还有另一个方法
foo(Runnable)
,因此派发程序无法明确地选择最具体的方法。(请参见我在Hemal的第二个答案中的评论。) 感谢大家的帮助。