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 game uses variables which 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 keyword, enum
, 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 in all uppercase.
private enum zombieTypes { REGULAR, RUNNER, CRAWLER, SPITTER, BLOATER, SNEAKER };
Note at this point 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, we had to declare an object/instance of the class.
At this point we have created a new type called zombieTypes
, but we have no instances of it. So, let's do that now.
zombieTypes therresa = zombieTypes.CRAWLER; zombieTypes angela = zombieTypes.SPITTER zombieTypes michelle = zombieTypes.SNEAKER /* Zombies are fictional creatures and any resemblance to real people is entirely coincidental */
We can then use ZombieTypes
in if
statements like this:
if(therresa = zombieTypes.CRAWLER){ // Move slowly }
Next is a sneak preview of the type of code we will soon be adding to the Snake
class in the next chapter. We will want to keep track of which way the snake is heading so will declare this enumeration.
// For tracking movement Heading private enum Heading { UP, RIGHT, DOWN, LEFT }
Don't add any code to the Snake
class yet. We will do so in the next chapter.
We can then declare an instance and initialize it like this:
Heading heading = Heading.RIGHT;
We can change it when necessary with code like this:
heading = Heading.UP
We can even use the type as the condition of a switch
statement (and we will) like this:
switch (heading) { case UP: // Going up break; case RIGHT: // Going right break; case DOWN: // Going down break; case LEFT: // Going left break; }
Don't add any code to the Snake
class yet. We will do so in the next chapter.
18.216.143.65