Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

Bounds

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 that 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content