Different ways for implementing a Generic Interface or extending a Generic Class

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Generics:
* Different ways for implementing a Generic Interface or extending a Generic Class

Table Of Contents
6 Generics
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap