Effective Java 的笔记,代码、英语原文为主,批注、翻译为辅。

Item 34: Use enums instead of int constants

用enum代替int常量

1
2
3
4
5
6
7
// The int enum pattern - severely deficient!
public static final int APPLE_FUJI = 0;
public static final int APPLE_PIPPIN = 1;
public static final int APPLE_GRANNY_SMITH = 2;
public static final int ORANGE_NAVEL = 0;
public static final int ORANGE_TEMPLE = 1;
public static final int ORANGE_BLOOD = 2;

Programs that use int enums are brittle. Because int enums are constant 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.

1
2
public enum Apple { FUJI, PIPPIN, GRANNY_SMITH }
public enum Orange { NAVEL, TEMPLE, BLOOD }

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.