THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

6.3. Enum Constant Declarations


The simplest enum constant declaration just gives a name for each enum constant, as you have seen. Such
enum constants implicitly define a public, static, and final field with the given name and of the same type as
the enum. These implicit fields are initialized by constructing an instance of the enum as described below. An
enum constant declaration cannot have modifiers applied to it, except for annotations (see Chapter 15).


6.3.1. Construction


An enum constant declaration that consists of only a name causes an object of the enum type to be created
with the (implicit or explicit) no-arg constructor. An enum can declare arbitrary constructors, just like any
other class. You select which constructor should be used for a particular enum constant by supplying
arguments that match the constructor parameter types:


enum Suit {
CLUBS("CLUBS"),
DIAMONDS("DIAMONDS"),
HEARTS("HEARTS"),
SPADES("SPADES");


String name;
Suit(String name) { this.name = name; }


public String toString() { return name; }
}


Here each Suit value has a name field set by the constructor that takes a String, and in each enum
constant declaration we provide the desired name argument. This is such a common thing to want with enum
constants, however, that this functionality has been built-in so you don't have to write the name strings
yourselfinvoking thename method on an enum constant will return its name as a String.


You can get a feel for how an enum is internally defined from the following pseudo-code, which shows a
mock class definition for the above Suit enum:


class Suit extends Enum // pseudo-code only
implements Comparable, Serializable {


public static final Suit CLUBS = new Suit("CLUBS");
public static final Suit DIAMONDS = new Suit("DIAMONDS");
public static final Suit HEARTS = new Suit("HEARTS");
public static final Suit SPADES = new Suit("SPADES");


String name;


Suit(String name) { this.name = name; }
public String toString() { return name; }


// ... compiler generated methods ...
}


There is a bit more to the detail, but the above gives you the general idea.

Free download pdf