Java Reference
In-Depth Information
private static class Node { public E data;
public Node next; } // ERROR
}
In the case of static fields, this restriction is very sensible. After the generic types
are erased, there is only a single field LinkedList.defaultValue , whereas
the static field declaration gives the false impression that there is a separate field
for each LinkedList<E> .
For static methods and inner classes, there is an easy workaround; simply add a
type parameter:
public class LinkedList<E>
{
. . .
public static <T> List <T> replicate( T value,
int n) { . . . } // OK
private static class Node <T> { public T data;
public Node <T> next; } // OK
}
CHAPTER SUMMARY
1. In Java, generic programming can be achieved with inheritance or with type
variables.
2. A generic class has one or more type variables.
3. Type variables can be instantiated with class or interface types.
4. Type variables make generic code safer and easier to read.
5. Type variables of a generic class follow the class name and are enclosed in
angle brackets.
6. Use type variables for the types of generic fields, method parameters, and
return values.
7. Generic methods can be defined inside ordinary and generic classes.
8. Supply the type variables of a generic method between the modifiers and the
method return type.
Search WWH ::




Custom Search