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

What built-in methods and customization options do Java enum types provide? | ComputerScienceOne | Bifalgorithm | Bifalgorithm