在Java中结合泛型类型参数和接口

在Java中结合泛型类型参数和接口,java,generics,inheritance,Java,Generics,Inheritance,和许多继承问题一样,我发现很难解释我想做什么。但是,一个快速(但奇特)的例子应该可以做到这一点: public interface Shell{ public double getSize(); } public class TortoiseShell implements Shell{ ... public double getSize(){...} //implementing interface method ... public T

和许多继承问题一样,我发现很难解释我想做什么。但是,一个快速(但奇特)的例子应该可以做到这一点:

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"
        ...
    }
}
公共接口外壳{
公共双getSize();
}
公营甲鱼壳{
...
公共双getSize(){…}//实现接口方法
...
公共乌龟getTortoise(){…}//新方法
...
}
公共类ShellViewer{
贝壳;
公共ShellViewer(S shell){
this.shell=shell;
...
}
}
公共类龟甲查看器扩展了ShellViewer{
公共玳瑁观赏者(T-tShell){
超级(tShell);//这里没有问题。。。
}
私有void removeTortoise(){
Tortoise t=tShell.getTortoise();//错误:编译器在“Shell”中找不到方法
...
}
}

编译器没有意识到我想要为
gettoroise()
使用特定的Shell实现。我哪里出错了?

根据您在这里给出的信息,问题在于:

public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer
你想要这个:

public class TortoiseShellViewer<T extends ToroiseShell> extends ShellViewer<T>
公共类OtteroishellViewer扩展了ShellViewer

removeTortoise中的tShell是什么?它是基类ShellViewer中类型Shell的实例吗?

假设Java泛型与C++的模板相同,这通常是错误的。您可能想消除
getTortoise
在一个位置返回一个double,在其他位置返回一个
Tortoise
的巨大障碍。谢谢编辑以供将来参考另一件有帮助的事情是在您显示的代码中包含所有相关信息。。。
ShellViewer
中的
tShell
字段声明在这里很重要,但是没有。我会记住的,谢谢!完美的非常感谢。我对仿制药的理解增加了10倍。这应该是龟甲的一个例子。或者,泛型类型T的一个实例,它扩展到了ToiseShell。对不起,如果读起来有点不舒服的话。我的实际代码被困在自己的应用程序中,无法在这里使用。。。
public class TortoiseShellViewer<T extends ToroiseShell> extends ShellViewer<T>