Sub topic 6
Generic Interfaces
An interface can have type parameters, just like a class. In earlier chapters you wrote generic classes such as Box<T> and Pair<K, V>. This chapter uses the same idea for interfaces. You will learn how to declare a generic interface, the main ways a class can implement one, and which generic interfaces from the Java library you will use most often.
What Is a Generic Interface?
An interface is a list of methods that a class promises to provide. A generic interface is an interface with one or more type parameters in angle brackets after its name. A type parameter is a placeholder for a type, such as T, that someone fills in later.
Here is a small generic interface for something that stores items:
public interface Storage<T> {
void put(T item);
T take();
boolean isEmpty();
}The interface leaves the item type open. It only says that whatever goes in with put comes out of take as the same type T. A Storage<String> holds strings. A Storage<Integer> holds integers.
Why Make an Interface Generic?
Without a type parameter, the interface would need to use Object:
public interface OldStorage {
void put(Object item);
Object take();
}Then every caller has to cast the result of take(), and the compiler cannot catch a wrong type. This is the same raw-type problem from the first chapter. With Storage<T>, the compiler knows the exact item type, so it removes the casts and rejects wrong types when the code is compiled.
Two Ways to Implement a Generic Interface
A class that implements a generic interface must decide what to do with T. It has two good choices.
Choice 1: Keep the type parameter
The class can be generic too and pass its own T along to the interface. Whoever uses the class then chooses the type.
class StackStorage<T> implements Storage<T> {
// ...
}Choice 2: Fix the type argument
A type argument is the actual type that replaces a type parameter, such as String. The class can pick one type argument for the interface. The class itself is then not generic.
class NameStorage implements Storage<String> {
// ...
}Inside NameStorage, every T from the interface becomes String. The method you write is public void put(String item), not put(T item).
The table compares the two choices.
| Approach | Class header | Who picks the type | Use it when |
|---|---|---|---|
| Keep the parameter | `class StackStorage<T> implements Storage<T>` | The code that creates the object | The class works the same for any type |
| Fix the argument | `class NameStorage implements Storage<String>` | The class author | The class only makes sense for one type |
A Complete Worked Example
Save this as StorageDemo.java, then compile and run it with javac StorageDemo.java and java StorageDemo.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
interface Storage<T> {
void put(T item);
T take();
boolean isEmpty();
}
// Choice 1: keep the type parameter
class StackStorage<T> implements Storage<T> {
private final Deque<T> items = new ArrayDeque<>();
@Override
public void put(T item) {
items.push(item);
}
@Override
public T take() {
return items.pop();
}
@Override
public boolean isEmpty() {
return items.isEmpty();
}
}
// Choice 2: fix the type argument to String
class NameStorage implements Storage<String> {
private final List<String> names = new ArrayList<>();
@Override
public void put(String item) {
names.add(item.trim().toUpperCase());
}
@Override
public String take() {
return names.remove(0);
}
@Override
public boolean isEmpty() {
return names.isEmpty();
}
}
public class StorageDemo {
public static void main(String[] args) {
Storage<Integer> numbers = new StackStorage<>();
numbers.put(10);
numbers.put(20);
int last = numbers.take(); // no cast needed
System.out.println("Took " + last); // Took 20
Storage<String> names = new NameStorage();
names.put(" ada ");
names.put("alan");
while (!names.isEmpty()) {
System.out.println(names.take()); // ADA, then ALAN
}
// numbers.put("thirty"); // compile error: String is not Integer
}
}Look at the variable types. Both variables use the interface type: Storage<Integer> and Storage<String>. This is common practice. Code that only knows about Storage<Integer> can work with any class that implements it.
NameStorage can only ever be a Storage<String>. Writing Storage<Integer> s = new NameStorage(); will not compile.
Generic Interfaces You Already Use
The Java library has many generic interfaces. These are the ones beginners meet first:
| Interface | Package | What it means |
|---|---|---|
| `List<E>` | `java.util` | An ordered collection of `E` |
| `Comparable<T>` | `java.lang` | "I can compare myself to a `T`" |
| `Comparator<T>` | `java.util` | "I can compare two `T` objects" |
| `Iterable<T>` | `java.lang` | "You can loop over me with for-each and get `T` items" |
| `Function<T, R>` | `java.util.function` | Takes a `T`, returns an `R` |
| `Supplier<T>` | `java.util.function` | Takes nothing, returns a `T` |
Comparable: a class compares to itself
A class often implements Comparable with itself as the type argument. This lets Java sort a list of that class.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Book implements Comparable<Book> {
private final String title;
private final int pages;
Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
@Override
public int compareTo(Book other) { // parameter is Book, not Object
return Integer.compare(this.pages, other.pages);
}
@Override
public String toString() {
return title + " (" + pages + ")";
}
}
public class BookSort {
public static void main(String[] args) {
List<Book> books = new ArrayList<>();
books.add(new Book("Long Novel", 900));
books.add(new Book("Short Story", 40));
books.add(new Book("Guide", 250));
Collections.sort(books);
System.out.println(books);
// [Short Story (40), Guide (250), Long Novel (900)]
}
}Because the type argument is Book, compareTo receives a Book. You can read other.pages directly with no cast.
Function and lambdas
A functional interface is an interface with exactly one abstract method. A lambda is a short way to write an object that implements one. Many functional interfaces are generic, and the type arguments tell the compiler the types of the lambda's input and output.
import java.util.function.Function;
import java.util.function.Supplier;
public class FunctionDemo {
public static void main(String[] args) {
Function<String, Integer> length = s -> s.length();
Supplier<String> greeting = () -> "hello";
Integer n = length.apply("generics"); // T is String, R is Integer
System.out.println(n); // 8
System.out.println(greeting.get()); // hello
}
}You never wrote the type of s. The compiler knows it is a String from Function<String, Integer>.
A Generic Interface Can Extend Another
An interface can extend a generic interface. It can pass its type parameter along, as a class can:
interface SizedStorage<T> extends Storage<T> {
int size();
}A class that implements SizedStorage<T> must provide put, take, isEmpty, and size, all using the same T.
Edge Cases and Common Mistakes
Forgetting the type argument
If you write class NameStorage implements Storage, without <String>, you get a raw type. The methods then use Object, and your put(String item) no longer counts as implementing put. The compiler reports that the class does not implement the interface's methods. Always write the type argument.
Implementing the same interface twice
A class cannot implement one generic interface twice with different type arguments:
// class Mixed implements Comparable<String>, Comparable<Integer> { }
// compile error: Comparable cannot be inherited with different argumentsThe reason is type erasure, which a later chapter explains. At runtime both would become the same plain Comparable.
Mismatched parameter names
The name of a type parameter is local to its declaration. class StackStorage<E> implements Storage<E> is valid and means the same thing as using T. What matters is that the E after implements is the same E the class declared.
Exercises
Exercise
Write a generic interface Converter<A, B> with one method B convert(A input). Then write a class LengthConverter that implements it so that it turns a String into its length as an Integer.
Show answer
interface Converter<A, B> { B convert(A input); } and class LengthConverter implements Converter<String, Integer> { @Override public Integer convert(String input) { return input.length(); } }. The class fixes A to String and B to Integer, so the method takes a String and returns an Integer.
Exercise
Given class Box<T> implements Storage<T>, which of these lines compile? (1) Storage<String> s = new Box<>(); (2) Storage<String> s = new Box<Integer>(); (3) Box<Double> b = new Box<>();
Show answer
Lines 1 and 3 compile. Line 2 fails because a Box<Integer> is a Storage<Integer>, not a Storage<String>. The type arguments must match.
Exercise
Why is the parameter of Book's compareTo method of type Book and not Object?
Show answer
Book implements Comparable<Book>, so the interface's T is replaced by Book. The method from the interface, int compareTo(T o), becomes int compareTo(Book o). You can then use the other book's fields without a cast.