Java, Software Development

Java – 3 ways to implement a Generic Interface

A Generic Interface uses formal type parameters. On the other hand, a traditional Java Interface doesn’t use Java Generics. There are three ways to implement generic interfaces in Java.

A Generic Interface

A generic interface looks something the following codes. The interface 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

Ignoring or removing formal type parameters is a terrible practice even when working with the latest JDK. We should only do this if we’re (still) working with JDK version 1.4 or lower. Java Generics was not available until JDK version 1.5. Consider the following codes.

The following class IgnoredFormalTypeParameters implements Moveable without using a formal type parameter. As a result, the class uses the Object type for the item variable.

If the codes are using Object types somewhere in an Interface definition, they are a recipe for a maintenance nightmare and probably need a Generic Interface.

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. Consider the following codes. They use <U> twice in the two locations.

3. Create A Class That Deals With Specific Non-generic Types

In this way, instead of using formal type parameters, we use an actual type. For example, use <Elephant> instead of <T>. Although we use a Generic Interface, the formal type parameter is a non-generic type.

When Do We Use the non-Generic Interfaces?

We use non-generic interfaces when we do not need to relate them to some specific types. For instance, marker interfaces like java.io.Serializable. These interfaces don’t need to be empty interfaces – no fields and methods in them. We use them to mark classes to conveniently pick out and process their instances.

References

This post is (now) part of a reboot Java tutorial.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like