Generic Class Hierarchies

A generic class can act as a superclass or be a subclass. In a generic hierarchy, any type arguments needed by a generic superclass must be passed up the hierarchy by all subclasses.

Using a Generic Superclass

 
class MyClass<T> {
  T ob;
  MyClass(T o) {
    ob = o;
  }
  T getob() {
    return ob;
  }
}
class MySubclass<T, V> extends MyClass<T> {
  V ob2;

  MySubclass(T o, V o2) {
    super(o);
    ob2 = o2;
  }

  V getob2() {
    return ob2;
  }
}
public class Main {
  public static void main(String args[]) {
    MySubclass<String, Integer> x = new MySubclass<String, Integer>("Value is: ", 99);
    System.out.print(x.getob());
    System.out.println(x.getob2());
  }
}
  

A Generic Subclass

It is perfectly acceptable for a non-generic class to be the superclass of a generic subclass.

 
class MyClass {
  int num;

  MyClass(int i) {
    num = i;
  }

  int getnum() {
    return num;
  }
}
class MySubclass<T> extends MyClass {
  T ob;
  MySubclass(T o, int i) {
    super(i);
    ob = o;
  }
  T getob() {
    return ob;
  }
}
public class Main {
  public static void main(String args[]) {
     MySubclass<String> w = new MySubclass<String>("Hello", 4);
    System.out.print(w.getob() + " ");
    System.out.println(w.getnum());
  }
}
  
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