2011-02-23 22 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