Generics and Limitations in Java - Bounds
(Page 2 of 5 )
In the process of discussing generics, we've already had to mention bounds a few times. A bound is a constraint on the type of a type parameter. Bounds use the extends keyword and some new syntax to limit the parameter types that may be applied to a generic type. In the case of a generic class, the bounds simply limit the type that may be supplied to instantiate it.
A type variable may extend a class or interface type, meaning that its instantiation must be of that type or a subtype:
class EmployeeList< T extends Employee > { ... }
Here, we made a generic EmployeeList type that can be instantiated only with Employee types. We could further require that the Employee type implement one or more interfaces using the special & syntax:
class EmployeeList< T extends Employee & Ranked & Printable > { ... }
The order of the & interface bounds is not significant, but only one class type can be specified and if there is one, it must come first. When a type has no specific bounds, the bound extends Object is implicit.
By applying bounds to our type, we not only limit the instantiations of the generic class but we make the type arguments more useful. Now that we know our type must extend some type or implement some set of interfaces, we can use variables and arguments declared with T by those other type names. Here is a somewhat contrived extension of our previous example:
class EmployeeList< T extends Employee & Ranked & Printable >
{
Ranked ranking;
List<Printable> printList = new ArrayList<Printable>();
public void addEmployee( T employee ) {
this.ranking = employee; // T as Ranked
printList.add( employee ); // T as Printable
}
}
Type variables can also refer to other type variables within the type declaration:
class Foo <A, B extends A> { ... }
We'll see a particularly vicious example of this later when we talk about the definition of the Enum class. We'll also see a more convenient technique for declaring how individual elements of a generic class relate to the parameter type when we cover wildcards in the next section.
Next: Erasure and Bounds (Working with Legacy Code) >>
More Java Articles
More By O'Reilly Media
|
This article was excerpted from chapter eight of the book Learning Java, third edition, written by Patrick Niemeyer and Jonathan Knudsen (O'Reilly; ISBN: 0596008732). Check it out today at your favorite bookstore. Buy this book now.
|
|