Java Reference
In-Depth Information
The values of an enumerated type, such as WorkDay.THURSDAY , are not String val-
ues. In fact, you should not care what kind of values they are. How they are imple-
mented is not relevant to being able to use the values of an enumerated type. All you
really need to know is that, for example, WorkDay.THURSDAY and WorkDay.FRIDAY are
different values and will test as being different if you compare them with == .
Although values of an enumerated type are not String values, they are used for
tasks that could be done by String values; but enumerated types work better than
String values for some tasks. You could use a String variable in place of a variable of
an enumerated type. For example, you could use
String meetingDay = "THURSDAY";
instead of
WorkDay meetingDay = WorkDay.THURSDAY;
However, using a String variable allows for the possibility of setting the variable equal
to a nonsense value, such as "SUNDAY" or "GaGa" for a work day, and to do so without the
computer issuing any warning statement. With an enumerated type, you know the only
possible values for a variable of that type are the values given in the enumerated type defi-
nition; if you try to give the variable a different value, you will get an error message.
An enumerated type is actually a class, and its values are objects of the class. Some meth-
ods that are automatically provided with every enumerated type are given in Display 6.14.
Display 6.14 Some Methods Included with Every Enumerated Type (part 1 of 2)
public boolean equals( Any_Value_Of_An_Enumerated_Type )
Returns true if its argument is the same value as the calling value. While it is perfectly legal to use
equals , it is easier and more common to use == .
E XAMPLE
For enumerated types, ( Value1 .equals( Value2 )) is equivalent to ( Value1 == Value2 ) .
public String toString()
Returns the calling value as a string. This is often invoked automatically. For example, this method is
invoked automatically when you output a value of the enumerated type using
System.out.println or when you concatenate a value of the enumerated type to a string.
See Display 6.15 for an example of this automatic invocation.
E XAMPLE
WorkDay.MONDAY.toString() returns "MONDAY" .
The enumerated type WorkDay is defined in Display 6.13.
Search WWH ::




Custom Search