2013-02-28 64 views
0

我的主要問題是圍繞何時使用,是什麼樣的區別以下時類,抽象,接口組合:使用的類,抽象,接口組合擴展

  1. <E>

  2. <E extends Interface>

  3. <? extends Interface>

下面顯示的是帶有一些代碼簽名的詳細問題:

此代碼使用Guava Forwarding Decorators來定義特定集合。

基本接口:

public interface AnimalSetInterface<E extends AnimalI> extends Set<E> 

這工作:

public interface AsiaI<E extends AnimalI> extends AnimalSetInterface<E> 

下面給出了一個錯誤:

public interface AsiaI<E> extends AnimalSetInterface<E> 

Bound mismatch: The type E is not a valid substitute for the bounded parameter of the type AnimalSetInterface

什麼我想了解的是,如果我有在基本界面上指定我只想要<E extends AnimalI>那麼爲什麼我必須再次指定AsiaI

我想了解泛型,同時最小化代碼。

此外,如果兩個類有這樣的代碼是否有合併/最小化的好辦法(刪除/泛型化樣板代碼)它:
亞洲:

public Asia(final ImmutableSet<E> animalSet){ 
    super(animalSet); 
} 

public static <E extends AnimalI> AsiaI<E> of(final ImmutableSet<E> animalSet){ 
    return new Asia(animalSet); 
} 

非洲:

public Africa(final ImmutableSet<E> animalSet){ 
    super(animalSet); 
} 

public static <E extends AnimalI> AfricaI<E> of(final ImmutableSet<E> animalSet){ 
    return new Africa(animalSet); 
} 

回答

3
public class Africa<E extends AnimalI> extends AnimalSetAbstract implements AfricaI 

public class Asia<E> extends AnimalSetAbstract implements AsiaI 

區別在於,在第一種情況下,您的ge neric類型必須擴展AnimalI 在第二種情況下,您的泛型類型可以是任何類。

+0

這就是我的想法,但下面的用法給出了錯誤(這是我想要的): 'final AsiaI a = new Asia(ImmutableSet.of()); \t // 不應該工作# – 2013-02-28 21:56:49

+0

@PranavShah你能否請你用你想要的行爲更新你的問題。到目前爲止我還不清楚你的問題是什麼。 – psabbate 2013-02-28 22:03:08

+0

進一步檢查,我看到發生了什麼事。在我的測試代碼中,我使用接口而不是類,因此我得到了錯誤,但現在我想我明白髮生了什麼 – 2013-02-28 22:03:19