Java Reference
In-Depth Information
Listing 18-2. Listing Name and Ordinal of Enum Type Constants
// ListEnumConstants.java
package com.jdojo.enums;
public class ListEnumConstants {
public static void main(String[] args) {
for(Severity s : Severity.values()) {
String name = s.name();
int ordinal = s.ordinal();
System.out.println(name + "(" + ordinal + ")");
}
}
}
LOW(0)
MEDIUM(1)
HIGH(2)
URGENT(3)
Superclass of an Enum Type
An enum type is similar to a Java class type. In fact, the compiler creates a class when an enum type is compiled.
You can treat an enum type as a class type for all practical purposes. However, there are some rules that apply only to
the enum type. An enum type can also have constructors, fields, and methods. Did I not say that an enum type cannot
be instantiated? (In other words, new Severity() is invalid.) Why do you need constructors for an enum type if it
cannot be instantiated?
Here is the reason why you need constructors for an enum type. An enum type is instantiated only in the code
generated by the compiler. All enum constants are objects of the same enum type. These instances are created and
named the same as the enum constants in the code generated by the compiler. The compiler is playing the tricks.
The compiler generates code for an enum type similar to the one shown below. The following sample code is just to
give you an idea what goes on behind the scenes. The actual code generated by the compiler may be different from
the one shown below. For example, the code for the valueOf() method gives you a sense that it compares the name
with enum constant names and returns the matching constant instance. In reality, the compiler generates code for a
valueOf() method that makes a call to the valueOf() method in the Enum superclass.
// Transformed code for Severity enum type declaration
package com.jdojo.enums;
public final class Severity extends Enum {
public static final Severity LOW;
public static final Severity MEDIUM;
public static final Severity HIGH;
public static final Severity URGENT;
 
Search WWH ::




Custom Search