Java Reference
In-Depth Information
Let's look at an example. The following version of the Direction enum overrides the
toString method, converting the uppercase enum name to lowercase:
1. public enum Direction {
2. NORTH, SOUTH, EAST, WEST;
3.
4. public String toString() {
5. return this.name().toLowerCase();
6. }
7. }
The name method is inherited from Enum and returns the corresponding element name.
Try to determine the output of the following statements:
10. for(Direction d : Direction.values()) {
11. System.out.print(d + “ “);
12. }
Printing the Direction variable d invokes toString behind the scenes, and the output of
this for-each loop is
north south east west
Declaring enum Constructors
An enum can also defi ne constructors, useful for enums that contain additional fi elds. For
example, suppose the following enum represents the types of ice cream cones a store sells,
and the number of scoops for each cone is also a constant. Because all of this information
regarding ice cream cones is known at compile time, this is a good scenario for using an enum.
1. public enum IceCream {
2. PLAIN(2),
3. SUGAR(3),
4. WAFFLE(5);
5.
6. private IceCream(int scoops) {
7. this.scoops = scoops;
8. }
9.
10. public final int scoops;
11. }
Search WWH ::




Custom Search