Chapter 10
Enums
In Chapter 2, “Language Fundamentals,” you learned that you sometimes use static final fields as enumerated values. Java 5 added a new type, enum, for enumerating values. This chapter presents a complete discussion of enum.
An Overview of Enum
You use enum to create a set of valid values for a field or a method. For example, in a typical application, the only possible values for the customerType are Individual or Organization. For the State field, valid values may be all the states in the US plus Canadian provinces, and some others. With enum, you can easily restrict your program to take only one of the valid values.
An enum type can stand alone or can be part of a class. You make it stand alone if it needs to be referenced from multiple places in your application. If it is only used from inside a class, enum is better made part of the class.
As an example, consider the CustomerType enum definition in Listing 10.1.
Listing 10.1: The CustomerType enum
package app10;
public enum CustomerType {
INDIVIDUAL,
ORGANIZATION
}
The CustomerType enum has two enumerated values: INDIVIDUAL and ORGANIZATION. Enum values are case sensitive and by convention are capitalized. Two enum values are separated by a comma and values can be written on a single line or multiple lines. The enum in Listing 10.1 is written in multiple lines to improve readability.
Using an enum is like using a class or an interface. For example, the Customer class in Listing 10.2 uses the CustomerType enum in Listing 10.1 as a field type.
Listing 10.2: The Customer class that uses CustomerType
package app10;
public class Customer {
public String customerName;
public CustomerType customerType;
public String address;
}
You can use a value in an enum just like you would a class's static member. For example, this code illustrates the use of CustomerType.
Customer customer = new Customer();
customer.customerType = CustomerType.INDIVIDUAL;
Notice how the customerType field of the Customer object is assigned the enumerated value INDIVIDUAL of the CustomerType enum? Because the customerType field is of typeCustomerType, it can only be assigned a value of the CustomerType enum.
The use of enum at first glance is no difference than the use of static finals. However, there are some basic differences between an enum and a class incorporating static finals.
Static finals are not a perfect solution for something that should accept only predefined values. For example, consider the CustomerTypeStaticFinals class in Listing 10.3.
Listing 10.3: Using static finals
package app10;
public class CustomerTypeStaticFinals {
public static final int INDIVIDUAL = 1;
public static final int ORGANIZATION = 2;
}
Suppose you have a class named OldFashionedCustomer that resembles the Customer class in Listing 10.2, but uses int for its customerType field.
The following code creates an instance of OldFashionedCustomer and assigns a value to its customerType field:
OldFashionedCustomer ofCustomer = new OldFashionedCustomer();
ofCustomer.customerType = 5;
Notice that there is nothing preventing you from assigning an invalid integer to customerType? In guaranteeing that a variable is assigned only a valid value, enums are better than static finals.
Another difference is that an enumerated value is an object. Therefore, it behaves like an object. For example, you can use it as a Map key. The section, “The Enum Class” discusses enums as objects in detail.
Enums in a Class
You can use enums as members of a class. You use this approach if the enum is only used internally inside the class. For example, the Shape class in Listing 10.4 defines a ShapeTypeenum.
Listing 10.4: Using an enum as a class member
package app10;
public class Shape {
private enum ShapeType {
RECTANGLE, TRIANGLE, OVAL
};
private ShapeType type = ShapeType.RECTANGLE;
public String toString() {
if (this.type == ShapeType.RECTANGLE) {
return "Shape is rectangle";
}
if (this.type == ShapeType.TRIANGLE) {
return "Shape is triangle";
}
return "Shape is oval";
}
}
The java.lang.Enum Class
When you define an enum, the compiler creates a class definition that extends the java.lang.Enum class. This class is a direct descendant of java.lang.Object. Unlike ordinary classes, however, an enum has the following properties:
/java%20book/images/squf.jpg)
/java%20book/images/squf.jpg)
/java%20book/images/squf.jpg)
/java%20book/images/squf.jpg)
Iterating Enumerated Values
You can iterate the values in an enum using the for loop (discussed in Chapter 3, “Statements”). You first need to call the values method that returns an array-like object that contains all values in the specified enum. Using the CustomerType enum in Listing 10.1, you can use the following code to iterate over it.
for (CustomerType customerType : CustomerType.values() ) {
System.out.println(customerType);
}
This prints all values in CustomerType, starting from the first value. Here is the result:
INDIVIDUAL
ORGANIZATION
Switching on Enum
The switch statement can also work on enumerated values of an enum. Here is an example using the CustomerType enum in Listing 10.1 and the Customer class in Listing 10.2:
Customer customer = new Customer();
customer.customerType = CustomerType.INDIVIDUAL;
switch (customer.customerType) {
case INDIVIDUAL:
System.out.println("Customer Type: Individual");
break;
case ORGANIZATION:
System.out.println("Customer Type: Organization");
break;
}
Note that you must not prefix each case with the enum type. The following would raise a compile error:
case CustomerType.INDIVIDUAL:
//
case CustomerType.ORGANIZATION:
//
Summary
Java supports enum, a special class that is a subclass of java.lang.Enum. Enum is preferred over static finals because it is more secure. You can switch on an enum and iterate its values by using the values method in an enhanced for loop.
Questions
1. How do you write an enum?
2. Why are enums safer than static final fields?
0 Comments