生效:選擇哪個重載調用是在編譯時進行的。 實施例:使用重載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