Chapter 13 Working with Java


Java Enumerated Types (Enums)

Java 5 supports enumerated types. These replace the old typesafe enum pattern, and are much more compact and easy to maintain. They can be used to list such collections of values as the days of the week or the suits of a deck of cards, or any fixed set of constants, such as the elements in a menu.

An enum is represented by a class with an <<enum>> stereotype.

Steps To create an enumerated type:

  1. Create a class in a class diagram or composite structure diagram, and double-click it to open its property sheet.
  2. On the General tab, select <<enum>> from the Stereotype list.
  3. Click the Attributes tab, and add as many attributes as necessary. These attributes have, by default, a data type of EnumConstant. For example, to create an enum type that contained standard mathematical operations, you would create four EnumConstants with the names "PLUS", "MINUS", "TIMES", and "DIVIDE".


    Note that, since a Java enum is a full featured class, you can also add other kinds of attributes to it by clicking in the Data Type column and selecting another type from the list.
  4. [optional] You can create an anonymous class for an EnumConstant by selecting its row on the Attributes tab and clicking the Properties tool to open its property sheet. On the General tab, click the Create tool next to the Enum class box to create the internal class.


    These anonymous classes will be displayed on the Inner Classifiers tab of the Enum class property sheet:


    The Operation enum class, with an anonymous class for each of its EnumConstants to allow for the varied arithmetic operations, could be represented in a class diagram as follows:


    The equivalent code would be like the following:

 


Copyright (C) 2007. Sybase Inc. All rights reserved.