生效:选择哪个重载调用是在编译时进行的。 实施例:使用重载vs覆盖,编译时间vs运行时间
class parentsecond{
public int getdouble(int x){ return x*2;}
}
class second extends parentsecond{
public int getdouble(int x){ return x*3;}
}
class third{
public static void calloverload(parentsecond s){
System.out.println(s.getdouble(4));
}
public static void calloverload(second s){
System.out.println(s.getdouble(4));
}
public static void main(String[] args){
third t=new third();
parentsecond s=new second();
t.calloverload(s);
}
}
回答是12. 并且行为为实例方法重载的方法相同的太。因此,在任何一种情况下,调用哪个重载方法的决定都是在运行时而不是编译时(它总是被调用的'second''getdouble)进行的。
因此,对于'Effective Java'中的这个特定项目有一些限制,我没有得到。
请帮助澄清'在编译时解决超载'的含义。
如何从这个上面不同:
....
class fourth{
public static String getCollection(Set<?> s){
return "Set";
}
public static String getCollection(Collection<?> c){
return "Collection";
}
public String getiCollection(Set<?> s){
return "Set";
}
public String getiCollection(Collection<?> c){
return "Collection";
}
public static void main(String[] args){
Collection<String> c=new HashSet<String>();
System.out.println(fourth.getCollection(c));
fourth f=new fourth();
System.out.println(f.getiCollection(c));
...
这个答案在这种情况下,始终是“收集”,而不是实际的运行时类型。
你能澄清你的问题吗? – 2013-04-06 02:32:09
问题是什么? – Buddha 2013-04-06 02:32:54
重新说明了问题,使其更清晰 – IUnknown 2013-04-06 02:37:24