Bounded type parameters
Last updated
Last updated
You can limit the type of objects that can be passed as arguments to generic classes, interfaces, and methods by using bounded type parameters.
Without a bounded type parameter (and explicit type casting), you can access only the members defined in the superclass of all classes—that is, class Object.
In the following example, the generic class Parcel won’t be able to access method getWeight() of class Gift:
To access members of class Gift in Parcel, you can limit the type of objects that can be passed to class Parcel (to Gift and its subclasses) by using bounded parameters (discussed next).
You can specify the bounds to restrict the set of types that can be used as type argu- ments to a generic class, interface, or method. It also enables access to the methods (and variables) defined by the bounds.
Let’s restrict the type of objects that can be passed to class Parcel to Gift so that the methods of class Parcel can access the methods and variables of class Gift. Because the definitions of classes Gift, Book, and Phone are the same as in the preceding section, they aren’t repeated in the following code:
A type parameter can have multiple bounds. The list of bounds consists of one class and/or multiple interfaces. The following example defines a generic class Parcel, the type parameter T of which has multiple bounds: