为什么它(显然)有所作为是否我通过null直接作为参数,或者传递一个Object,我分配的价值 null?
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)");
}
Run Code Online (Sandbox Code Playgroud)
换句话说,为什么第二次调用(已注释掉)foo(...)未调度到foo(Object)?
更新:我使用Java 1.6.我可以毫无问题地编译Hemal的代码,但我仍然无法编译.我看到的唯一区别是,Hemal的方法是静态的,而我的方法则不是.但我真的不明白为什么这应该有所作为......?
更新2:解决了.我的班级中有另一个方法foo(Runnable),因此调度员无法明确地选择最具体的方法.(请参阅我在Hemal的第二个答案中的评论.)感谢大家的帮助.
为什么每次打印时都遵循程序I'm string而不是I'm object.或I'm int.?
public class Demo {
public Demo(String s){
System.out.println("I'm string");
}
public Demo(int i){
System.out.println("I'm int.");
}
public Demo(Object o){
System.out.println("I'm object.");
}
public static void main(String[] args) {
new Demo(null);
}
}
Run Code Online (Sandbox Code Playgroud)
另外,如果我取代int用Integer.它给出了错误,The constructor Demo(String) is ambiguous.为什么?
我最近遇到了两个重载问题,我找不到答案,也没有java环境来运行一些测试代码.我希望有人可以通过汇编一份java编译器遵循的所有规则列表来帮助我进行重载,或者交替指向我已经存在的列表.
首先,当两个方法只有最终的varargs参数不同时,在什么情况下每个方法都被调用,你可以在没有任何args的情况下调用varargs方法吗?
private void f(int a) { /* ... */ }
private void f(int a, int... b) { /* ... */ }
f(12); // calls the former? I would expect it to
f(12, (int[])null); // calls latter, but passes null for b?
// Can I force the compiler to call the second method in the same fashion
// as would happen if the first method didn't exist?
Run Code Online (Sandbox Code Playgroud)
第二个问题,当两个方法因为彼此继承而被调用的类型不同时?我希望调用最多的派生版本,并允许调用另一个版本.
interface A {}
class B implements A {}
class C implements A …Run Code Online (Sandbox Code Playgroud)