将泛型类型参数与Java中的接口相结合

时间:2011-02-23 18:52:40

标签: java generics inheritance

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

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的特定实现。我哪里出错?

3 个答案:

答案 0 :(得分:4)

根据您在此处提供的内容,问题是:

public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer

未正确指定ShellViewer(通用)。它应该是:

public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer<T>

答案 1 :(得分:4)

你想要这个:

public class TortoiseShellViewer<T extends ToroiseShell> extends ShellViewer<T>

答案 2 :(得分:0)

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