与许多继承问题一样,我很难解释我想要做什么。但是,快速(但奇特)的例子应该做的伎俩:将泛型类型参数与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