Java Reference
In-Depth Information
Discussion
To enumerate means to list all the values. You often know that a small list of possible values
is all that's wanted in a variable, such as the months of the year, the suits or ranks in a deck
of cards, the primary and secondary colors, and so on. The C programming language
provided an enum keyword:
enum { BLACK, RED, ORANGE} color;
Java was criticized in its early years for its lack of enumerations, which many developers
have wished for. Many have had to develop custom classes to implement the “typesafe enu-
meration pattern.”
But C enumerations are not “typesafe”; they simply define constants that can be used in any
integer context. For example, this code compiles without warning, even on gcc 3 with -Wall
(all warnings), whereas a C++ compiler catches the error: [ 31 ]
enum { BLACK, RED, ORANGE} color;
enum { READ, UNREAD } state;
/*ARGSUSED*/
int main(int argc, char *argv[]) {
color = RED;
color = READ; // In C this will compile, give bad results
return 0;
}
To replicate this mistake in Java, one needs only to define a series of final int values; it
will still not be typesafe. By typesafe I mean that you cannot accidentally use values other
than those defined for the given enumeration. The definitive statement on the “typesafe enu-
meration pattern” is probably the version defined in Item 21 of Joshua Bloch's book Effective
Java (Addison-Wesley). All modern Java versions include enumerations in the language; it is
no longer necessary to use the code from Bloch's book. Bloch was one of the authors of the
Typesafe Enumeration specification ( enum keyword), so you can be sure that Java now does
a good job of implementing his pattern. These enum s are implemented as classes, subclassed
(transparently, by the compiler) from the class java.lang.Enum . Unlike C, and unlike the
“series of final int” implementation, Java typesafe enumerations:
▪ Are printable (they print as the name, not as an underlying int implementation).
 
Search WWH ::




Custom Search