与许多继承问题一样,我发现很难解释我想做什么。但是一个快速(但奇特)的例子应该可以解决问题:
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()
使用特定的 Shell 实现。我哪里出错了?
最佳答案
根据您在此处提供的内容,问题在于:
public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer
没有正确指定 ShellViewer
(通用)。应该是:
public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer<T>
关于java - 将泛型类型参数与 Java 中的接口(interface)相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5095612/