簡體   English   中英

Java中的泛型,擴展接口

[英]Generics in java, extending interfaces

在下面的代碼中:

class A<T extends InterfaceA & InterfaceB>

“ T應該是InterfaceA的一種”是什么意思?

例如下面的代碼:

class A<T extends Number>

表示T可以是int,double或任何其他數字類型。 誰能給我一個例子來解釋第一個代碼?

它說T必須是同時實現interfaceAinterfaceB接口的類型。

您的第二個示例說T必須是僅實現Number接口的任何類型。

class A<T extends interfaceA & interfaceB>含義

T受兩個接口限制。 因此,傳遞給T的任何類型參數都必須實現interfaceAinterfaceB

示例程序供您理解:-

interface X{
public void eat();
}

interface Y{
public void drink();
}

class XYZ implements X,Y{
@Override
public void eat(){
    System.out.println("I am eating.");   
}
@Override
public void drink(){
    System.out.println("I am drinkin too!");
}    
}

class A<T extends X & Y> {
public void display(){
     XYZ x=new XYZ();
     x.eat();
     x.drink();
     System.out.println("Type of XYZ is "+x.getClass().getName());
    }  
}

public class Sample1{
public static void main(String[] args) {
 A<XYZ> a=new A<>();
 a.display();
}    
}

這意味着傳遞給T的參數的類型必須實現接口X和Y。

如給定代碼所示:

A<XYZ> a=new A<>(); //here only XYZ(substituted in place of T) can be passed because it implements both interface X and interface Y

我希望這能幫助您理解並指出差異!!!

我將使用@shekhar suman的示例,但我將更改最后一堂課和主要課程:

class A<T extends X & Y> {
  public void display(T t){
       t.eat();
       t.drink();
       System.out.println("Type of T is "+t.getClass().getName());
  }  
}

public static void main(String[] args) {
   A<XYZ> a=new A<>();
   a.display(new XYZ());
}    

如果沒有這樣的擴展:Class A <T> Class A是一個通用類,則接受任何T類。

但是,在類A <T擴展的情況下,InterfaceA和InterfaceB> T可以是同時實現interfaceA和interfaceB的任何類。

換句話說,您要確保T不是任何隨機類,並且滿足某些條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM