2013-08-02 39 views
3

我想要一個處理實現特定接口的任何類型的列表的方法。在這種情況下,Java是否'擴展'也意味着'implements'?

public interface Encryptable { 
    public void encrypt() throws Exception ; 
} 

class DomainClass implements Encryptable { 

    String name ; 

    public void encrypt() throws Exception { 
     try { 
      name = CryptoUtils.encrypt(name); 
     } 
    } 
} 

此實用方法可以對實現Encryptable的任何域類的List進行加密。

public static void encryptList (Collection<? extends Encryptable> listToEncrypt ) { 
    for (Encryptable objToEncrypt: listToEncrypt) { 
     try { 
      objToEncrypt.encrypt() ; 
     } catch (Exception e) { 
     } 
    } 
} 

我寫了一個測試應用程序,這似乎工作。我關心的是Java關鍵字'extends'。我的課程不擴展他們實施它的可加密。我所寫的是否真的有效,或者我是做錯事情的副作用的犧牲品,但卻得到正確的答案。

+1

你正在做的事情是正確的。 Oracle Java教程中的[Lesson:Interfaces and Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/index.html)介紹了這一點。 –

+0

http://stackoverflow.com/questions/10971888/implements-vs-extends-in-generics-in-java – StormeHawke

回答

4

是的,你做的是正確的事情。您使用的上界通配符,根據docs

聲明一個上界通配符,使用通配符(「?」),接着 由extends關鍵字,隨後其上限。注意,在這種情況下,在一般意義上使用 擴展是指「擴展」(如在類中)或「實現」(如在接口中)。

但是在使用multiple bounds with type Parameters時應該謹慎。在多邊界類型參數中,您必須先指定類名稱然後再指定接口。

+1

請注意,通配符不能使用多個邊界,只需鍵入參數即可。 –

+1

@Paul Bellora非常感謝你糾正我。我已經更新了答案以反映它。 – Prabhaker

4

你做得對。這有點模棱兩可,但是你是對的。但請記住,您始終可以使用界面而不是類,然後extends的確有意義。

1

你寫得對。在泛型中只允許使用關鍵字「extended」,無論是從類中擴展還是實現接口。

4

一如既往,JLS已經回答了這個問題。

爲泛型類型參數語法見Section 8.1.2

TypeParameters: 
    <TypeParameterList> 

TypeParameterList: 
    TypeParameterList , TypeParameter 
    TypeParameter 

而且Section 4.4TypeParameter語法:

TypeParameter: 
    TypeVariable TypeBoundopt 

TypeBound: 
    extends TypeVariable 
    extends ClassOrInterfaceType AdditionalBoundListopt 

AdditionalBoundList: 
    AdditionalBound AdditionalBoundList 
    AdditionalBound 

AdditionalBound: 
    & InterfaceType 

你可以看到它使用extends關鍵字爲ClassOrInterfaceType,在TypeBound。對於類型參數和通配符的語法也請參閱Section 4.5.1

相關問題