Java Reference
In-Depth Information
Sample Run:
Line 8: My grade: A
Line 9: The ordinal value of myGrade is 0
Line 10: myGrade name: A
Line 11: My sport: BASKETBALL
Line 12: The ordinal value of mySport is 1
Line 13: mySport name: BASKETBALL
Line 14: Sports:
BASEBALL's ordinal value is 0
BASKETBALL's ordinal value is 1
FOOTBALL's ordinal value is 2
GOLF's ordinal value is 3
HOCKEY's ordinal value is 4
SOCCER's ordinal value is 5
TENNIS's ordinal value is 6
The preceding program works as follows. The statements in Lines 1 and 2 define the
enum type Grades and Sports , respectively. The statement in Line 4 declares myGrade
to be a reference variable of the type Grades , and the statement in Line 5 declares
mySport to be a reference variable of the type Sports . The statement in Line 6 assigns
the object A to myGrade , and the statement in Line 7 assigns the object BASKETBALL to
mySport .
The statement in Line 8 outputs myGrade , the statement in Line 9 uses the method
ordinal to output the ordinal value of myGrade , and the statement in Line 10 uses the
method name to output the name of myGrade .
The statement in Line 11 outputs mySport , the statement in Line 12 uses the method
ordinal to output the ordinal value of mySport , and the statement in Line 13 uses the
method name to output the name of mySport .
The foreach loop in Line 15 outputs the value of Sports and their ordinal values. Note
that the method values , in the expression Sports.values() , returns the value of the
enum type Sport as a list. The loop control variable sp ranges over those values one-by-
one, starting at the first value.
The beginning of this section noted that an enum type is a special type of class, and the
enum constants are reference variables to the objects of that enum type. Because each
enum type is a class, in addition to the enum constants, it can also contain constructors,
( private ) data members, and methods. Before describing enumeration type or enum in
more detail, let us note the following:
1. Enumeration types are defined using the keyword enum rather than class .
2. enum types are implicitly final because enum constants should not be modified.
3. enum constants are implicitly static .
Search WWH ::




Custom Search