Generic interfaces

A generic interface enables you to abstract over types. In this section, you’ll see how to define and implement generic interfaces.

DEFINING A GENERIC INTERFACE:

The declaration of a generic interface includes one or more type parameters. Let’s look at an example of a generic interface that can accept multiple type parameters: the MyMap interface accepts two type parameters and defines methods put() and get(). You can compare the MyMap interface to a simplified version of the Map inter- face, defined in the java.util package:

NONGENERIC CLASS IMPLEMENTING A GENERIC INTERFACE:

When a nongeneric class implements a generic interface, the type parameters don’t follow the class name. For the implemented interface, the type parameters are replaced by actual types:

In the preceding example, MapLegendNonGeneric is a nongeneric class which implements generic interface MyMap (defined in the previous section).

When implementing a generic interface, take note of the type parameters and how they are used in method declarations (method parameters and return types). The methods of an implementing class must implement or override all the interface methods. In the following example, class MapLegendNonGeneric won’t compile because it doesn’t override the abstract method get(String) in MyMap (the return type of get() is declared to be String, not Integer):

A nongeneric class can implement a generic interface by replacing its type parameters with actual types.

Code :

package com.gs.corejava.generics;

interface MyMap<K,V>{
	void put(K key, V value);
    V get(K key);
}

class MapLegendNonGeneric implements MyMap<String,Integer>{

	public void put(String key, Integer value) {		
	}
	public Integer get(String key) {
		return null;
	}
	
}

public class NonGenericClassWithGenericInterface {

}

GENERIC CLASS IMPLEMENTING A GENERIC INTERFACE:

Here’s an example of declaring a generic class that implements a generic MyMap inter- face. To pass the type parameter information to a class, the type parameters must follow both the name of the class and the interface implemented by the class:

You might also choose a combination. In the following examples, the classes define only one parameterized type, V or K. While implementing the MyMap interface, the classes pass actual parameters (String or Integer) to one of the interface’s parameterized types (K or V):

It’s important to use a correct combination of type parameters and actual parameters in the method declarations. The following class won’t compile because class Map- LegendGeneric doesn’t implement method put(K key, String value) from the MyMap interface:

Generic classes and interfaces are collectively referred to as generic types.

Last updated