O'Reilly logo

Java 5.0 Tiger: A Developer's Notebook by David Flanagan, Brett McLaughlin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Enumerated Types

In Java 1.4 and below, there were two basic ways to define new types: through classes and interfaces. For most object-oriented programming, this would seem to be enough. The problem is that there are still some very specific cases where neither is these is sufficient, most commonly when you need to define a finite set of allowed values for a specific data type. For instance, you might want a type called Grade that can only be assigned values of A, B, C, D, F, or Incomplete. Any other values are illegal for this type. This sort of construct is possible prior to Tiger, but it takes a lot of work, and there are still some significant problems.

Since we’re good developers and try our best to avoid a lot of work whenever possible, Sun finally helped us out with the new enumerated type (generally referred to simply as an enum). This chapter deals with enums: how to create, use, and program with them.

Creating an Enum

Creating an enumerated type involves three basic components, at a minimum:

  • The enum keyword

  • A name for the new type

  • A list of allowed values for the type

There are several optional components that may be defined as well:

  • An interface or set of interfaces that the enum implements

  • Variable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required