與許多繼承問題一樣,我很難解釋我想要做什麼。但是,快速(但奇特)的例子應該做的伎倆:將泛型類型參數與Java中的接口結合起來
public interface Shell{
public double getSize();
}
public class TortoiseShell implements Shell{
...
public double getSize(){...} //implementing interface method
...
public Tortoise getTortoise(){...} //new method
...
}
public class ShellViewer<S extends Shell>{
S shell;
public ShellViewer(S shell){
this.shell = shell;
...
}
}
public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer{
public TortoiseShellViewer(T tShell){
super(tShell); //no problems here...
}
private void removeTortoise(){
Tortoise t = tShell.getTortoise(); //ERROR: compiler can not find method in "Shell"
...
}
}
編譯器不承認,我想用一個具體的實施殼牌爲getTortoise()
。我哪裏錯了?
大多數情況下,您錯誤地認爲Java泛型與C++的模板相同。 – 2011-02-23 18:55:30
可能想要刪除'getTortoise'的巨大紅色鯡魚,在其他地方返回一個double和一個'Tortoise'。 – 2011-02-23 19:04:36
Woops。謝謝!編輯以備將來參考 – MattLBeck 2011-02-23 19:08:29