Java Reference
In-Depth Information
Static initialization of this enum type would throw a
NullPointerException
because the
static
variable
colorMap
is uninitialized when the constructors for the enum constants
run. The restriction above ensures that such code won't compile.
Note that the example can easily be refactored to work properly:
import java.util.Map;
import java.util.HashMap;
enum Color {
RED, GREEN, BLUE;
static final Map<String,Color> colorMap =
new HashMap<String,Color>();
static {
for (Color c : Color.values())
colorMap.put(c.toString(), c);
}
}
The refactored version is clearly correct, as static initialization occurs top to bottom.
Example 8.9.2-2. Enum Type With Members
enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
Coin(int value) { this.value = value; }
private final int value;
public int value() { return value; }
}
Each enum constant arranges for a different value in the field
value
, passed in via a
constructor. The field represents the value, in cents, of an American coin. Note that
there are no restrictions on the type or number of parameters that may be declared by
an enum type's constructor.
A
switch
statement is useful for simulating the addition of a method to an enum type
from outside the type. This example “adds” a
color
method to the
Coin
type, and prints
a table of coins, their values, and their colors.
class Test {
public static void main(String[] args) {
for (Coin c : Coin.values())