Generic Interfaces

Generic interfaces are specified like generic classes.

 
interface MinMax<T extends Comparable<T>> {
  T max();
}
class MyClass<T extends Comparable<T>> implements MinMax<T> {
  T[] vals;
  MyClass(T[] o) {
    vals = o;
  }
  public T max() {
    T v = vals[0];
    for (int i = 1; i < vals.length; i++) {
      if (vals[i].compareTo(v) > 0) {
        v = vals[i];
      }
    }
    return v;
  }
}

public class Main {
  public static void main(String args[]) {
    Integer inums[] = { 3, 6, 2, 8, 6 };
    Character chs[] = { 'b', 'r', 'p', 'w' };
    MyClass<Integer> a = new MyClass<Integer>(inums);
    MyClass<Character> b = new MyClass<Character>(chs);
    System.out.println(a.max());
    System.out.println(b.max());
  }
}
  

In general, if a class implements a generic interface, then that class must also be generic.

If a class implements a specific type of generic interface, such as shown here:

 
class MyClass implements MinMax<Integer> { // OK
  

then the implementing class does not need to be generic.

Here is the generalized syntax for a generic interface:

 
interface interface-name<type-param-list> { // ...
  

type-param-list is a comma-separated list of type parameters. When a generic interface is implemented, you must specify the type arguments, as shown here:

 
class class-name<type-param-list> 
   implements interface-name<type-arg-list> {
  
Home 
  Java Book 
    Language Basics  

Generics:
  1. Generic Class
  2. Generic Bounded Types
  3. Generic Wildcard Arguments
  4. Generic Bounded Wildcards
  5. Generic Method
  6. Generic Constructors
  7. Generic Interfaces
  8. Raw Types and Legacy Code
  9. Generic Class Hierarchies
  10. Run-Time Type Comparisons Within a Generic Hierarchy
  11. Overriding Methods in a Generic Class
  12. Generic Restrictions
  13. Generic Array Restrictions