Java Reference
In-Depth Information
Chapter 13
Generic Class Types
WHAT YOU WILL LEARN IN THIS CHAPTER:
• What a generic type is
• How you define a generic type
• How you specify type parameters for a generic type
• What parameter type bounds are and how you use them
• What wildcard type specifications are and how you use them
• How you define bounds for a wildcard
• How you define and use parameterized methods
Generic class types are not a separate capability from the class and interface types that you have seen in earlier
chapters. The facility for defining generic class and interface types is an extension of the ordinary definition
of classes and interfaces that you are familiar with that enables you to define families of classes and inter-
faces.
WHAT ARE GENERIC TYPES?
A generictype , which is also referred to as a parameterizedtype , is a class or interface type definition that has
one or more type parameters. You define an actual class or interface type from a generic type by supplying a
type argument for each of the type parameters that the generic type has. It'll be easier to understand what this
means with a concrete example of where and how you could apply the concept.
I'm sure you recall the LinkedList class that you first saw in Chapter 6 and used in an example in Chapter
12. You used the LinkedList class to encapsulate a linked list of Point objects, but the idea of a linked list
applies to any set of objects that you want to organize in this way. A linked list is just one example of classes
that define objects for organizing other objects of a given type into a collection in some way. Such classes
are described as collection classes for obvious reasons, and in Chapter 14 you see a variety of these that are
defined in the java.util package. Of course, you have already seen the EnumSet collection class in use for
file I/O, and you learn more about this class later in Chapter 14, too.
The LinkedList class that you implemented in Chapter 6 can organize objects of any given type into a
linked list. This clearly has the advantage that the code for a single class defines a linked list class that you
can use for objects of any kind, but it has significant disadvantages, too. When you were adding Point objects
to a LinkedList object, nothing in the code prevented you from adding a Line object, or indeed any type of
object, to the same linked list. Of course, if you were to do this inadvertently, the result would be a disaster,
because when you retrieved objects from the list, you would not know that some of the objects were not of
Search WWH ::




Custom Search