Different ways for implementing a Generic Interface or extending a Generic Class
suggest changeSuppose 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 MyGenericInterface, 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 a generic class whose type parameter is passed through to MyGenericInterface:
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 that implements MyGenericInterface as a raw type:
public class MyGenericSubclass implements MyGenericInterface {
public void foo(Object t) { } // type T has been replaced by Object
// other possible methods
}
This is not recommended. It mixes a raw type with a generic interface, and the compiler warns about unchecked conversion. The source still compiles so that pre-generics code keeps compiling. The class file runs on a current JVM.
All the ways listed above are also allowed when using a generic class as a supertype instead of a generic interface.