Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You might expect that aStack2<Object>
is a supertype of aStack2<String>
, becauseObject
is a supertype ofString
. 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:
You might choose to create a list of strings and use this method to print all the strings:public void printAll(Collection<Object> c) { for (Object o : c) { System.out.println(o); } }If you try this you will notice that the last statement produces a compilation error. SinceList<String> list = new ArrayList<String>(); ... printall(list); //errorArrayList<String>
is not subtype ofCollection<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 worksList<Object>
is compatible withCollection<Object>
because the two types are instantiations of a generic supertype and its subtype and the instantiations are for the same type argument, namelyObject
.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.