Java Reference
In-Depth Information
6.13.1 Enumerated types
Code 6.9 shows a Java enumerated type definition called CommandWord .
Code 6.9
An enumerated type for
command words
/**
* Representations for all the valid command words for the game.
*
* @author Michael K├Âlling and David J. Barnes
* @version 2011.08.09
*/
public enum CommandWord
{
// A value for each command word, plus one for unrecognized
// commands.
GO, QUIT, HELP, UNKNOWN;
}
In its simplest form, an enumerated type definition consists of an outer wrapper that uses the
word enum rather than class and a body that is simply a list of variable names denoting the
set of values that belong to this type. By convention, these variable names are fully capitalized.
We never create objects of an enumerated type. In effect, each name within the type definition
represents a unique instance of the type that has already been created for us to use. We refer to
these instances as CommandWord.GO , CommandWord.QUIT , etc. Although the syntax for using
them is similar, it is important to avoid thinking of these values as being like the numeric class
constants we discussed in Section 5.13. Despite the simplicity of their definition, enumerated
type values are proper objects and are not the same as integers.
How can we use the CommandWord type to make a step toward decoupling the game logic of
zuul from a particular natural language? One of the first improvements we can make is to the
following series of tests in the processCommand method of Game :
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return false;
}
String commandWord = command.getCommandWord();
if(commandWord.equals("help")) {
printHelp();
}
else if(commandWord.equals("go")) {
goRoom(command);
}
else if(commandWord.equals("quit")) {
wantToQuit = quit(command);
}
 
Search WWH ::




Custom Search