Chapter 3. Enumerated Types
Note
In this chapter:
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
keywordA 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 ...
Get Java 5.0 Tiger: A Developer's Notebook 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.