Java Reference
In-Depth Information
You declare a variable of an enum type the same way you declare a variable of a class type.
// Declare defectSeverity variable of the Severity enum type
Severity defectSeverity;
You can assign null to an enum type variable, like so:
Severity defectSeverity = null;
What other values can you assign to an enum type variable? An enum type defines two things:
The enum constants, which are the only valid values for its type
The order for those constants
The Severity enum type defines four enum constants. Therefore, a variable of the Severity enum type can have
only one of the four values— LOW , MEDIUM , HIGH , and URGENT— or null . You can use dot notation to refer to the enum
constants by using the enum type name as the qualifier. The following snippet of code assigns values to a variable of
Severity enum type:
Severity low = Severity.LOW;
Severity medium = Severity.MEDIUM;
Severity high = Severity.HIGH;
Severity urgent = Severity.URGENT;
You cannot instantiate an enum type. The following code that attempts to instantiate the Severity enum type
results in a compile-time error:
Severity badAttempt = new Severity(); // A compile-time error
an enum type acts as a type as well as a factory. It declares a new type and a list of valid instances of that type
as its constants.
Tip
An enum type also assigns an order number (or position number), called ordinal, to all of its constants. The
ordinal starts with zero and it is incremented by one as you move from first to last in the list of constants. The first
enum constant is assigned the ordinal value of zero, the second of 1, the third of 2, and so on. The ordinal values
assigned to constants declared in Severity enum type are 0 to LOW , 1 to MEDIUM , 2 to HIGH , and 3 to URGENT . If
you change the order of the constants in the enum type body, or add new ones, their ordinal values will change
accordingly.
Each enum constant has a name. The name of an enum constant is the same as the identifier specified for the
constant in its declaration. For example, the name for the LOW constant in the Severity enum type is “ LOW.
You can read the name and the ordinal of an enum constant using the name() and ordinal() methods,
respectively. Each enum type has a static method named values() that returns an array of constants in the order they
are declared in its body. The program in Listing 18-2 prints the name and ordinal of all enum constants declared in
the Severity enum type.
 
 
Search WWH ::




Custom Search