Enumerations
An enumeration is a list of all the possible values in a logical collection. Java enum
is a great way of, well, enumerating things. For example, if our app uses variables that can only be in a specific range of values, and if those values could logically form a collection or a set, then enumerations are probably appropriate to use. They will make your code clearer and less error-prone.
To declare an enum
in Java, we use the enum
keyword, followed by the name of the enumeration, followed by the values the enumeration can have, enclosed in a pair of curly braces {...}
.
As an example, examine this enumeration declaration. Note that it is a convention to declare the values from the enumeration all in uppercase:
private enum zombieTypes { REGULAR, RUNNER, CRAWLER, SPITTER, BLOATER, SNEAKER };
Note at this point that we have not declared any instances of zombieTypes
, just the type itself. If that sounds odd, think about it like this. We created the Apple
class, but to use it,...