Java – 3 ways to implement a Generic Interface

Last Updated on

A generic interface uses formal type parameters. There are 3 ways to implement generic interfaces in Java.

A Generic Interface

A generic interface looks something like this. It has a name and a formal type parameter T. The other parts of the interface use T as they would use an actual type, e.g., String.

Ways to Implement Generic Interface

1. Ignore or Remove Formal Type Parameters

Nowadays this is bad practice. We only do this when we are using JDK version 1.4 or lower because Generics was not available until JDK version 1.5. The following class IgnoredFormalTypeParameters implements Moveable without using a formal type parameter. As a result, it uses Object type.

If you are using an IDE, it will probably warn you about using Object type.

Implementing generic interface without formal type parameter

2. Create a Generic Class

Another way is to create a generic class that implements the generic interface. The class definition uses the same formal type parameters twice. One after the class name and another after the interface name it implements. The codes below uses <U> twice in the mentioned locations.

3. Create a class that deals with specific non-generic types

In this way instead of using format type parameters, we use an actual type. For example, use <Elephant> instead of <T>.



Karl San Gabriel

Professional Software Developer