Concept
What built-in methods and customization options do Java enum types provide?
ComputerScienceOne / More Tricks
"Every enum type has some additional built-in methods that you can use. For example, there is a values() method that can be called on the enum that returns an array of the enum’s values. You can use an enhanced for loop to iterate over them, for example,\n\nfor(Day d : Day.values() {\n\nSystem.out.println(d.name());\n\n}\n\nIn the example above, we used another feature: each enum value has a name() method that returns the value as a String. This example would end up printing the following.\n\nSUNDAY\n\nMONDAY\n\nTUESDAY\n\nWEDNESDAY\n\nTHURSDAY\n\nFRIDAY\n\nSATURDAY\n\nOf course, we may want more human-oriented representations. To do this we could override the class’s toString() method to return a better string representation. For example:\n\npublic String toString() {\n\nif(this == SUNDAY) {\n\nreturn \"Sunday\";\n\n} else if(this == MONDAY) {\n\nreturn \"Monday\";\n\n}\n\n...\n\n} else {\n\nreturn \"Saturday\";\n\n}\n\n}\n\nBecause enum types are full classes in Java, many more tricks can be used that leverage the power of classes including using additional state and constructors. We will cover these topics later."
Related Ideas
- How do you declare and use an enumerated type in Java?ComputerScienceOne · More Tricks
- What common methods do Java classes inherit?ComputerScienceOne · Usage
- What does the completed Java Student class example contain?ComputerScienceOne · Example
- How does Java use variables and collections in enhanced for loops?ComputerScienceOne · Enhanced For Loops
- How can you iterate over Java arrays?ComputerScienceOne · Basic Usage
- What are enhanced for loops in Java?ComputerScienceOne · Enhanced For Loops
- How are classes declared and named in Java?ComputerScienceOne · Program Structure
- How do you declare an enumerated type in C?ComputerScienceOne · Enumerated Types