Java Reference
In-Depth Information
You would agree that representing the severity types using integer constants is difficult to maintain. That was the
only easily implemented solution available before Java 5 to define enumerated constants. You could have solved this
problem effectively before Java 5. However, the amount of code you had to write was disproportionate to the problem.
The enum type in Java 5 solves this problem in a simple and effective way.
According to the Merriam-Webster online dictionary, the term “enumerate” means “to specify one after another.”
This is exactly what the enum type lets you do. It lets you specify constants in a specific order. The constants defined in
an enum type are instances of that enum type. You define an enum type using the keyword enum . Its simplest general
syntax is
<access-modifier> enum <enum-type-name> {
// List of comma separated names of enum constants
}
The value for < access-modifiers> is the same as the access modifier for a class: public , private , protected ,
or package-level. The <enum-type-name> is a valid Java identifier. The body of the enum type is placed within braces
following its name. The body of the enum type can have a list of comma-separated constants and other elements that
are similar to the elements you have in a class, for example, instance variables, methods, etc. Most of the time, the
enum body includes only constants. The following code declares an enum type called Gender , which declares two
constants, MALE and FEMALE :
public enum Gender {
MALE, FEMALE; // The semi-colon is optional in this case
}
It is a convention to name the enum constants in uppercase. the semicolon after the last enum constant is
optional if there is no code that follows the list of constants.
Tip
Listing 18-1 declares a public enum type called Severity with four enum constants: LOW , MEDIUM , HIGH , and
URGENT .
Listing 18-1. Declaration of a Severity Enum
// Severity.java
package com.jdojo.enums;
public enum Severity {
LOW, MEDIUM, HIGH, URGENT;
}
A public enum type can be accessed from anywhere in the application. Just like a public class, you need to
save the code in Listing 18-1 in a file named Severity.java . When you compile the code, the compiler will create a
Severity.class file. Note that except for the use of the enum keyword and the body part, everything for the Severity
enum type looks the same as if it is a class declaration. In fact, Java implements an enum type as a class. The compiler
does a lot of work for an enum type and generates code for it that is essentially a class. You need to place an enum type
in a package as you have been placing all classes in a package. You can use an import statement to import an enum
type, as you import a class type, into a compilation unit.
 
 
Search WWH ::




Custom Search