Parametric Polymorphism (Java)

A generic class or interface has one or more type parameters.

Example: Trees

class Node<Data> {
   private Data info;
   private Node<Data> parent;
   public Node(Data i, Node<Data> p) {
      info = i;
      parent = p;
   }
   public Node(Data i) { this(i, null); }
   public Node() { this(null); }
   public Data getInfo() { return info; }
   public void setInfo(Data i) { info = i; }
   public Node<Data> getParent() { return parent; }
   public void setParent(Node<Data> p) { parent = p; }
   public String toString() { return "[" + info + "]"; }
}

Suppose we wanted to implement binary search trees. In this case the values for Data must be restricted to subtypes of the Comparable interface:

class Node<Data implements Comparable> { ... }

Warning:

S <: T does NOT imply Node<S> <: Node<T>

However:

Node<S> <: Node<?> for every S

For example:

class TreeUtils {
   public static void displayPath(Node<?> node) {
      while(node != null) {
         System.out.print(node + " ");
         node = node.getParent();
      }
      System.out.println();
   }
   // etc.
}

Usage:

class TestTree {
   public static void main(String[] args) {
      Node<String> nfl = new Node<String>("NFL");
      Node<String> afc = new Node<String>("AFC", nfl);
      Node<String> nfc = new Node<String>("NFC", nfl);
      Node<String> raiders = new Node<String>("Raiders", afc);
      Node<String> jets = new Node<String>("Jets", afc);
      TreeUtils.displayPath(raiders);
   }
}

Output:

[Raiders] [AFC] [NFL]