Java Reference
In-Depth Information
This defines a new type, Day , for variables that can store only one or other of the values specified between
the braces. The names Monday , Tuesday , and so on through to Sunday are called enumerationconstants , and
they identify the only values that are allowed for variables of type Day . In fact these names correspond to
integer values, starting from 0 in this case, but they are not the same as integer variables because they exist
only within the context of the enumeration, Day .
Note the absence of a semicolon at the end of the definition of the Day enumeration. Because you are
defining a type here, no semicolon is required after the closing brace. I used a capital D at the beginning of
the type name, Day , because by convention types that you define begin with a capital letter. The names for
the enumeration constants would usually be written beginning with a small letter, but in this case I used a
capital letter at the beginning because that's how the days of the week are usually written. You could just as
well write the enumeration constants with a small letter.
With this new type, you can now define the variable weekday like this:
Day weekday = Day.Tuesday;
This declares the variable weekday to be of type Day and initializes it with the value, Tuesday . Note that
the enumeration constant that provides the initial value for weekday must be qualified with the name of the
enumeration type here. If you leave the qualifier out, the compiler does not recognize the constant. There
is a way to get around this, but you have to wait until Chapter 5 to find out about it. A variable of a given
enumeration type can only be set to one or other of the enumeration constants that you defined for the type.
An enumeration can contain as many or as few enumeration constants as you need. Here's an enumeration
type for the months in the year:
enum Month { January, February, March , April , May , June,
July , August , September, October, November, December }
You could define a variable of this type like this:
Month current = Month.September; // Initialize to September
If you later want to change the value stored in the variable, you can set it to a different enumeration con-
stant:
current = Month.October;
The current variable now contains the enumeration constant, October .
Let's see an enumeration in action in an example.
TRY IT OUT: Using an Enumeration
Here's a program that defines the Day enumeration and some variables of that type.
public class TryEnumeration {
// Define an enumeration type for days of the week
enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,
Sunday}
Search WWH ::




Custom Search