Java Reference
In-Depth Information
7-1. Defining a Fixed Set of Related Con-
stants
Problem
You need a type that can represent a fixed set of related constants.
Solution
Use an
enum
type. The following example defines an
enum
type, called
FieldType
,
to represent various form fields you might find on the GUI of an application:
// See BasicFieldType.java
public enum FieldType { PASSWORD, EMAIL_ADDRESS,
PHONE_NUMBER, SOCIAL_SECURITY_NUMBER }
This is the simplest form of an
enum
type, which will often suffice when all that is
needed is a related set of named constants. In the following code, a
field
variable of
type
FieldType
is declared and initialized to the
FieldType.EMAIL_ADDRESS
enum
constant. Next, the code prints the results of calling various methods that are
defined for all
enum
types:
FieldType field = FieldType.EMAIL_ADDRESS;
System.out.println("field.name(): " + field.name());
System.out.println("field.ordinal(): " + field.ordinal());
System.out.println("field.toString(): "
+ field.toString());
System.out.println("field.isEqual(EMAIL_ADDRESS): " +
field.equals(FieldType.EMAIL_ADDRESS));
System.out.println("field.isEqual(\"EMAIL_ADDRESS\"'): "
+ field.equals("EMAIL_ADDRESS"));
System.out.println("field == EMAIL_ADDRESS: " + (field ==
FieldType.EMAIL_ADDRESS));