Effective Java 的笔记,代码、英语原文为主,批注、翻译为辅。
Item 34: Use enums instead of int constants
用enum代替int常量
|
|
Programs that use int enums are brittle. Because
int enums
areconstant variables
(编译时常量), their int values are compiled into the clients that use them. If the value associated with an int enum is changed, its clients must be recompiled. If not, the clients will still run, but their behavior will be incorrect.
Luckily, Java provides an alternative that avoids all the shortcomings of the int and string enum
patterns and provides many added benefits. It is the enum type.
|
|
The basic idea behind Java’s enum types is simple:
they are classes that export one instance
for each enumeration constant
via a public static final
field.
Enum types are effectively final, by virtue of having no accessible constructors.
Because clients can neither create instances of an enum type nor extend it, there can be no instances but the declared enum constants. In other words, enum types are instance-controlled
. They are a generalization of singletons
, which are essentially single-element enums.