實現通用介面(或擴充套件通用類)的不同方法
假設已宣告以下通用介面:
public interface MyGenericInterface<T> {
public void foo(T t);
}
下面列出了實現它的可能方法。
具有特定型別的非泛型類實現
選擇一個特定的型別來替換 MyGenericClass
的形式型別引數 <T>
並實現它,如下例所示:
public class NonGenericClass implements MyGenericInterface<String> {
public void foo(String t) { } // type T has been replaced by String
}
這個類僅處理 String
,這意味著使用具有不同引數的 MyGenericInterface
(例如 Integer
,Object
等)將無法編譯,如下面的程式碼片段所示:
NonGenericClass myClass = new NonGenericClass();
myClass.foo("foo_string"); // OK, legal
myClass.foo(11); // NOT OK, does not compile
myClass.foo(new Object()); // NOT OK, does not compile
通用類實現
使用正式型別引數 <T>
宣告另一個通用介面,該引數實現 MyGenericInterface
,如下所示:
public class MyGenericSubclass<T> implements MyGenericInterface<T> {
public void foo(T t) { } // type T is still the same
// other methods...
}
請注意,可能使用了不同的正式型別引數,如下所示:
public class MyGenericSubclass<U> implements MyGenericInterface<U> { // equivalent to the previous declaration
public void foo(U t) { }
// other methods...
}
原始類類實現
宣告一個非泛型類,它將 MyGenericInteface
實現為原始型別 (根本不使用泛型),如下所示:
public class MyGenericSubclass implements MyGenericInterface {
public void foo(Object t) { } // type T has been replaced by Object
// other possible methods
}
建議不要使用這種方式,因為它在執行時不是 100%安全,因為它將 (子類的) 原始型別與 ( 泛型 ) 泛型混合在一起,這也令人困惑。現代 Java 編譯器將通過這種實現發出警告,然而程式碼 - 出於與舊 JVM(1.4 或更早版本)的相容性原因 - 將進行編譯。
當使用泛型類作為超型別而不是通用介面時,也允許使用上面列出的所有方法。