A generic type can be bounded with multiple class data types. The class types that qualify are subclasses of a specified data type or implementations of an interface. For example, we might wish to create a vector or array list and call a method in a generic class to process the data. Both the
Vector classes are implementations of the
List interface. Therefore the bounds of the generic parameter are the implementations of
List. To learn how to write type parameters with multiple bounds in Java, follow these four steps.
- Open your text editor and type in the following Java statements:
GenericsMultipleBounds(line 15) is defined with the clause
<T extends List>which means the generic type is bounded by implementations of the
Vectorare common examples of
Listimplementations and are referred to as collections. The main method instantiates two
GenericMultipleBoundsobjects. An array list is passed to the first object's
displaymethod. A vector is passed to the second object's
displaymethod will print the first item of the collection that was passed.
- Save your file as WriteTypeParametersWithMultipleBounds.java.
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
- Type in the command to run your program and hit Enter. Notice in the output that the first item of the array list was displayed followed by the first item stored in the vector.