Java Generic Interfaces

Introduction

We can create generic interfaces.

Here is the generalized syntax for a generic interface:

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

Here, type-param-list is a comma-separated list of type parameters.

When a generic interface is implemented, you must specify the type arguments:

class class-name<type-param-list>  
    implements  interface-name<type-arg-list> { 
// A generic interface example. 
interface MyInterface<T extends Comparable<T>> {
  T min();//  ww w .ja  v  a 2  s .  c  o m

  T max();
}

class MyClass<T extends Comparable<T>> implements MyInterface<T> {
  T[] vals;

  public MyClass(T[] o) {
    vals = o;
  }

  public T min() {
    T v = vals[0];

    for (int i = 1; i < vals.length; i++) {
      if (vals[i].compareTo(v) < 0) {
        v = vals[i];
      }
    }
    return v;
  }

  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[] = { 'd', 'e', 'm', 'o' };

    MyClass<Integer> iob = new MyClass<Integer>(inums);
    MyClass<Character> cob = new MyClass<Character>(chs);

    System.out.println("Max value in inums: " + iob.max());
    System.out.println("Min value in inums: " + iob.min());

    System.out.println("Max value in chs: " + cob.max());
    System.out.println("Min value in chs: " + cob.min());
  }
}



PreviousNext

Related