Java & J2EE Page 2 - Java Comes of Age |
Personally, the omission of "proper" enumerations in earlier versions of Java really annoyed me. I still can't believe how Java survived so long without it. In versions of Java prior to 1.5, the typical approach to represent the suit of a playing card would be something like the following:
The problem is that this representation is not type-safe: it is too easy to mix up an int that represents the suit of a card with another int such as a loop counter. It could be made type-safe by writing a class with a private constructor:
In this case, the only instances of the class Suit that will ever exist are those that are created inside the class itself. It guarantees type-safety, but is long-winded and not easy to read. In Java 1.5, you can create an enumerated type in a single line as follows:
Think of the enum keyword as an alternative to class, as similar restrictions apply. As with classes, public enumerations must be in a file named after the enumeration, but the same restriction does not apply to package level enumerations. Inner enumerations (if that is the correct terminology) are also permitted, and can be public:
You can refer to the inner enumeration and its allowed values using the dot notation: Card.CardValue.ace, for example.
blog comments powered by Disqus |