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
- How do you declare an enumerated type in C?ComputerScienceOne · Enumerated Types
- Why are enumerated types better than arbitrary integer error codes?ComputerScienceOne · Enumerated Types
- How do enumerated types represent named values in C?ComputerScienceOne · Using Enumerated Types for Error Codes
- How can enumerated types be used for error codes in C?ComputerScienceOne · Using Enumerated Types for Error Codes