| This enum Goes to Eleven |
|---|
|
Although Java syntax borrowed heavily from C++, there are many C++ features that Java chose to omit. At times, the lack of a particular feature makes Java programs cumbersome to implement. One such feature is the ability to define enumerated types, such as those declared with the C++ enum keyword.
An enumerated type holds a set of values defined by the programmer. Usually these values behave much like integers, and as such have an implicit ordering. The principal benefit derived from an enumerated type is the ability to restrict the value of a variable to a discrete set, eliminating the need for explicit range checking and leveraging compiler type-checking for error detection. You might represent a set of discrete volume levels in C++ as follows:
The most common way to implement this in Java is to define a set of static final integers in an interface and have any class that requires those values either implement the interface or explicitly reference the values. For example:
Here any variable of type integer can represent a volume level. We have captured the ordering of the values, but have lost both type safety and the limitation of the domain to a discrete, programmer-defined set. In the C++ example, if a variable is of type One way to simulate enumerated types in pure object-oriented programming is to declare a new empty class for each enumerated type, and then to create static final members that are instances of the new type and represent the discrete range. Our Java implementation becomes:
Defined in this way, a Stereo instance can only have a
This solves the ordering problem and the manipulation of the values as integers. You can determine ordering with
You may be wondering why we added the As you can see, it is quite a lot of work to get the functionality of enumerated types in Java. Simply using integer constants will be sufficient for most programs, but when value restriction and type safety become issues, you will likely have to resort to some variation of this more complicated solution. Daniel F. Savarese |