实现通用接口(或扩展通用类)的不同方法

假设已声明以下通用接口:

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(例如 IntegerObject 等)将无法编译,如下面的代码片段所示:

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 或更早版本)的兼容性原因 - 将进行编译。

当使用泛型类作为超类型而不是通用接口时,也允许使用上面列出的所有方法。