An enumeration is a range of (usually) distinct symbolic constants.
Until Java 1.5, an enumeration was simply an informal grouping of static final variables:
public static final int RED = 0; public static final int REDAMBER = 1; public static final int GREEN = 2; public static final int AMBER = 3;
(Java also has a class Enumeration
,
which serves a different, unrelated purpose.)
Java 1.5 introduced a specific concept for enumerations:
public enum LightState { RED, REDAMBER, GREEN, AMBER }
These are distinct instances of a class type, and don't correspond to integer values (apart from their order).
C has a concept with a similar syntax, but with semantics rather more like static finals:
enum light { RED, REDAMBER, GREEN, AMBER };
This defines a new type enum light
, and defines the
symbols RED
for 0
, REDAMBER
for 1
, GREEN
for 2
,
and AMBER
for 3
.
The first symbol is assigned the value 0
, and each subsequent symbol is assigned
the next integer. However, a symbol can be assigned a
particular value:
enum light { RED = 3, REDAMBER, GREEN = 1, AMBER };
This also implies that REDAMBER
is 4
, and that AMBER
is 2
.
If a new type is not required, the tag can be omitted:
enum { RED, REDAMBER, GREEN, AMBER };
The symbols can be used in any expression, and may be
assigned to any integral type, not just the enum
type. For this reason,
the tag is rarely used.
C enum
s are no more
sophisticated than that. In contrast to Java, the symbols
are not objects, and cannot take parameters.