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

Case Study: The Enum Class

If you take a look at the definition of the java.lang.Enum class in Java 5 or later, you’ll see a rather bizarre-looking generic type declaration:

    Enum< E extends Enum<E> > { ... }

In trying to parse this, you may be hampered by two thoughts, which we’ll try to dispel right away. First, upon quick inspection this may appear to be recursive. The type variable E seems to be defined as something that’s not yet finished being defined. But it’s not really. We often have mathematical equations of the form x = function( x ) and they are not recursive. What they really call for is a special value of x that satisfies the condition. Next, although it’s pretty clear that E is a subtype of some formulation of the generic Enum type, you may jump to the conclusion that E itself must be a generic type. Remember that concrete types can extend generics just as well as generics can.

With these thoughts in mind, let’s hunt for some arrangement that satisfies these bounds. Let’s focus only on the bound for a moment:

    E extends Enum<E>

E is a subclass of some parameterization of Enum and, in particular, the parameterization of Enum on the subclass type itself. To say this again, what it does is to require that any invocations of the Enum type are by subclasses of some parameterization of the Enum type. And specifically, the parameterizations of the Enum type supply their own type as the type parameter to their parent, Enum. What kind of class satisfies this condition?

    class
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