Bounded type parameters

You can limit the type of objects that can be passed as arguments to generic classes, interfaces, and methods by using bounded type parameters.

NEED FOR BOUNDED TYPE PARAMETER:

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).

DEFINING BOUNDED TYPE PARAMETERS:

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:

For a bounded type parameter, the bound can be a class, interface, or enum, but not an array or a primitive type. All cases use the keyword extends to specify the bound. If the bound is an interface, the implements keyword isn’t used.

DEFINING MULTIPLE BOUNDS:

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:

For a type parameter with multiple bounds, the type argument must be a subtype of all bounds.

Last updated