The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Relationships Among Generics

You might expect that a Stack2<Object> is a supertype of a Stack2<String>, because Object is a supertype of String. In fact, no such relationship exists for instantiations of generic types. The lack of a super-subtype relationship among instantiations of a generic type when the type arguments possess a super-subtype relationship can make programming polymorphic methods challenging.

Suppose you would like to write a method that prints out a collection of objects, regardless of the type of objects contained in the collection:

public void printAll(Collection<Object> c) {
    for (Object o : c) {
        System.out.println(o);
    }
}
You might choose to create a list of strings and use this method to print all the strings:
List<String> list = new ArrayList<String>();
...
printall(list);   //error 
If you try this you will notice that the last statement produces a compilation error. Since ArrayList<String> is not subtype of Collection<Object> it cannot be passed as argument to the print method even though the two types are instantiations of the same generic type with type arguments related by inheritance. On the other hand, instantiations of generic types related by inheritance for the same type argument are compatible:
public void printAll(Collection<Object> c) {
    for (Object o : c) {
        System.out.println(o);
    }
}
List<Object> list = new ArrayList<Object>();
...
printall(list);   //this works 
List<Object> is compatible with Collection<Object> because the two types are instantiations of a generic supertype and its subtype and the instantiations are for the same type argument, namely Object.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.