Java Reference
In-Depth Information
Chapter 18
Enum Types
In this chapter, you will learn
•
What enum types are
•
How to declare enum types and enum constants
•
How to use enums in switch statements
•
How to associate data and methods to enum constants
•
How to declare nested enums
•
How to implement interfaces to an enum type
•
How to perform a reverse lookup for enum constants
EnumSet
to work with ranges of enum constants
•
How to use
What Is an Enum Type?
An enum (also known as enumeration and enumerated data type) lets you create an ordered list of constants as a
type. Before we discuss what an enum is and why we need it, let's consider a problem and solve it using Java features
that were available before Java 5. Suppose you are working on a defect tracking application in which you need to
represent the severity of a defect. The application lets you specify the severity of a defect as low, medium, high, and
urgent. A typical way to represent the four types of severity before Java 5 was to declare four
int
constants in a class,
say
Severity
, as shown:
public class Severity {
public static final int LOW = 0;
public static final int MEDIUM = 1;
public static final int HIGH = 2;
public static final int URGENT = 3;
}
Suppose you want to write a utility class named
DefectUtil
that has a method to compute the projected
turnaround days for a defect based on its severity. The code for the
DefectUtil
class may look like the following:
public class DefectUtil {
public static int getProjectedTurnaroundDays(int severity) {
int days = 0;