Java Reference
In-Depth Information
How It Works
A common pattern for representing a fixed set of related constants is to define each
constant as an int, String , or some other type. Often, these constants are defined
in a class or interface whose sole purpose is to encapsulate constants. In any case, con-
stants are sometimes defined with the static and final modifiers, as follows:
// Input field constants
public static final int PASSWORD = 0;
public static final int EMAIL_ADDRESS = 1;
public static final int PHONE_NUMBER = 2;
public static final int SOCIAL_SECURITY_NUMBER = 3;
There are multiple problems with this pattern, the primary one being the lack of
type safety. By defining these constants as int s, it is possible to assign an invalid
value to a variable that is supposed to be allowed to hold only one of the constant val-
ues:
int inputField = PHONE_NUMBER; // OK
inputField = 4; // Bad - no input field constant with
value 4; compiles without error
As you can see, there will be no compiler error or warning produced to inform you
of this invalid value assignment. Chances are, you will discover this at runtime, when
your application tries to use inputField , and an incorrect value is assigned to it. In
contrast, Java enum types provide compile-time type safety. That is, if one attempts to
assign a value of the wrong type to an enum variable, it will result in a compiler error.
In the solution this recipe, the FieldType.EMAIL_ADDRESS enum constant was
assigned to the field variable. Attempting to assign a value that isn't of type
FieldType naturally results in a compiler error:
FieldType field = FieldType.EMAIL_ADDRESS; // OK
field = "EMAIL_ADDRESS"; // Wrong type - compiler error
An enum is simply a special type of class. Under the covers, Java implements an
enum type as a subclass of the abstract and final java.lang.Enum class.
Thus, an enum type cannot be instantiated directly (outside of the enum type) or ex-
tended. The constants defined by an enum type are actually instances of the enum
Search WWH ::




Custom Search