Java Reference
In-Depth Information
▪ Are almost as fast as int constants, but the code is more readable.
▪ Can be easily iterated over.
▪ Utilize a separate namespace for each enum type, so you don't have to prefix each with
some sort of constant name, like ACCOUNT_SAVINGS , ACCOUNT_CHECKING , etc.
Enum constants are not compiled into clients, giving you the freedom to reorder the con-
stants within your enum without recompiling the client classes. That does not mean you
should, however; think about the case where objects that use them have been persisted, and
the person designing the database mapping used the numeric values of the enums. Bad idea
to reorder then!
Additionally, an enum type is a class, so it can, for example, implement arbitrary interfaces,
and you can add constructors, fields, and methods to an enum class.
Compared to Bloch's Typesafe Enum pattern in the topic:
▪ Java enums are simpler to use and more readable (those in the topic require a lot of meth-
ods, making them cumbersome to write).
▪ Enums can be used in switch statements.
So there are many benefits and few pitfalls.
The enum keyword is at the same level as the keyword class in declarations. That is, an
enum may be declared in its own file with public or default access. It may also be declared in-
side classes, much like nested or inner classes (see Using Inner Classes ) . Media.java , shown
in Example 8-2 , is a code sample showing the definition of a typesafe enum .
Example 8-2. structure/Media.java
public enum Media {
BOOK, MUSIC_CD, MUSIC_VINYL, MOVIE_VHS, MOVIE_DVD;
}
Notice that an enum is a class; see what javap thinks of the Media class:
C:> javap Media
Compiled from "Media.java"
public class Media extends java.lang.Enum{
public static final Media BOOK;
public static final Media MUSIC_CD;
Search WWH ::




Custom Search