Java Reference
In-Depth Information
An enumerated type is a special kind of class, and the variables of an enumer-
ated type are object variables. As such, there are a few methods associated with
all enumerated types. The ordinal method returns the numeric value associated
with a particular enumerated type value. The name method returns the name of
the value, which is the same as the identifier that defines the value.
Listing 3.6 shows a program called IceCream that declares an enumerated type
and exercises some of its methods. Because enumerated types are special types of
classes, they are not defined within a method. They can be defined either at the
class level (within the class but outside a method), as in this example, or at the
outermost level.
We explore enumerated types further in Chapter 6.
LISTING 3.6
//********************************************************************
// IceCream.java Author: Lewis/Loftus
//
// Demonstrates the use of enumerated types.
//********************************************************************
public class IceCream
{
enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee,
rockyRoad, mintChocolateChip, cookieDough}
//-----------------------------------------------------------------
// Creates and uses variables of the Flavor type.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Flavor cone1, cone2, cone3;
cone1 = Flavor.rockyRoad;
cone2 = Flavor.chocolate;
System.out.println ("cone1 value: " + cone1);
System.out.println ("cone1 ordinal: " + cone1.ordinal());
System.out.println ("cone1 name: " + cone1.name());
System.out.println ();
System.out.println ("cone2 value: " + cone2);
System.out.println ("cone2 ordinal: " + cone2.ordinal());
System.out.println ("cone2 name: " + cone2.name());
 
Search WWH ::




Custom Search