Java Language Different ways for implementing a Generic Interface (or extending a Generic Class)


Example

Suppose the following generic interface has been declared:

public interface MyGenericInterface<T> {
    public void foo(T t);
}

Below are listed the possible ways to implement it.


Non-generic class implementation with a specific type

Choose a specific type to replace the formal type parameter <T> of MyGenericClass and implement it, as the following example does:

public class NonGenericClass implements MyGenericInterface<String> {
    public void foo(String t) { } // type T has been replaced by String
}

This class only deals with String, and this means that using MyGenericInterface with different parameters (e.g. Integer, Object etc.) won't compile, as the following snippet shows:

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

Generic class implementation

Declare another generic interface with the formal type parameter <T> which implements MyGenericInterface, as follows:

public class MyGenericSubclass<T> implements MyGenericInterface<T> {
    public void foo(T t) { } // type T is still the same
    // other methods...
}

Note that a different formal type parameter may have been used, as follows:

public class MyGenericSubclass<U> implements MyGenericInterface<U> { // equivalent to the previous declaration
    public void foo(U t) { }
    // other methods...
}

Raw type class implementation

Declare a non-generic class which implements MyGenericInteface as a raw type (not using generic at all), as follows:

public class MyGenericSubclass implements MyGenericInterface {
    public void foo(Object t) { } // type T has been replaced by Object
    // other possible methods
}

This way is not recommended, since it is not 100% safe at runtime because it mixes up raw type (of the subclass) with generics (of the interface) and it is also confusing. Modern Java compilers will raise a warning with this kind of implementation, nevertheless the code - for compatibility reasons with older JVM (1.4 or earlier) - will compile.


All the ways listed above are also allowed when using a generic class as a supertype instead of a generic interface.