2011-02-23 80 views
4

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

+1

大多数情况下,您错误地认为Java泛型与C++的模板相同。 – 2011-02-23 18:55:30

+0

可能想要删除'getTortoise'的巨大红色鲱鱼,在其他地方返回一个double和一个'Tortoise'。 – 2011-02-23 19:04:36

+1

Woops。谢谢!编辑以备将来参考 – MattLBeck 2011-02-23 19:08:29

回答

4

基于你这里给出过什么,问题是:

public class TortoiseShellViewer<T extends TortoiseShell> extends ShellViewer 

不指定ShellViewer(这是通用的)正确。它应该是:

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

完美!谢谢。我对泛型的理解只增加了10倍。 – MattLBeck 2011-02-23 19:03:04

4

你想这样的:

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

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

+0

它应该是一个TortoiseShell的实例。或者,扩展TotoiseShell的泛型类型T的一个实例。对不起,如果它有点模糊读取。我的实际代码在自己的应用程序中太麻烦了,无法在此使用... – MattLBeck 2011-02-23 19:11:23