It is important to note that a generic class is shared by all its instances regardless of its actual concrete type. Suppose stack1 and stack2 are created as follows :
GenericStack<String> stack1 = new GenericStack<String>(); GenericStack<Integer> stack2 = new GenericStack<Integer>();
Although GenericStack<String> and GenericStack<Integer> are two types, there is only one GenericStack class loaded into the JVM. stack1 and stack2 are both instances of GenericStack . So the following statements display true :
System.out.println(stack1 instanceof GenericStack); System.out.println(stack1 instanceof GenericStack<?>); System.out.println(stack2 instanceof GenericStack); System.out.println(stack2 instanceof GenericStack<?>);
But the expression stack1 instanceof GenericStack<String> is wrong. Since GenericStack<String> is not stored as a separate class in the JVM, it makes no sense to use it in casting or instanceof expression. The following expressions are illegal:
stack1 instanceof GenericStack<String> (GenericStack<String>)stack1
Since all instances of a generic class have the same runtime class, the static variables and methods of a generic class are shared by all its instances. Therefore, it is illegal to refer to a generic type parameter for a class in a static method or initializer. For example, the following code is illegal:
public class Test <E> { public static void m( E o1) { // illegal } static { E o2; // illegal } }