6.6 Enumeration as a Class

The sands are number’d that make up my life.

—WILLIAM SHAKESPEARE, Henry VI, Part 3

Chapter 3 introduced enumerations and mentioned that the compiler creates a class when it encounters an enumeration. This section talks about that class. Although you should consider using enumerations in your programs, the ideas in this section are not central to the presentation in the rest of the book.

Let’s define a simple enumeration for the suits of playing cards, as follows:

enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}

The compiler creates a class Suit. The enumerated values are names of public static objects whose type is Suit. As you know, you reference each of these values by prefacing its name with Suit and a dot, as in the ...

Get Java: An Introduction to Problem Solving and Programming, 8th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.