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
Java Book
Language Basics
Generics:
- Generic Class
- Generic Bounded Types
- Generic Wildcard Arguments
- Generic Bounded Wildcards
- Generic Method
- Generic Constructors
- Generic Interfaces
- Raw Types and Legacy Code
- Generic Class Hierarchies
- Run-Time Type Comparisons Within a Generic Hierarchy
- Overriding Methods in a Generic Class
- Generic Restrictions
- Generic Array Restrictions