Java Reference
In-Depth Information
Code 6.10
Associating command
strings with enumerated
type values
/**
* Representations for all the valid command words for the game
* along with a string in a particular language.
*
* @author Michael Kölling and David J. Barnes
* @version 2011.08.10
*/
public
enum
CommandWord
{
// A value for each command word along with its
// corresponding user interface string.
GO(
"go"
), QUIT(
"quit"
), HELP(
"help"
), UNKNOWN(
"?"
);
// The command string.
private
String commandString;
/**
* Initialize with the corresponding command string.
* @param commandString The command string.
*/
CommandWord(String commandString)
{
this
.commandString = commandString;
}
/**
* @return The command word as a string.
*/
public
String toString()
{
return
commandString;
}
}
The main points to note about this new version of
CommandWord
are that:
■
Each type value is followed by a parameter value—in this case, the text of the command as-
sociated with that value.
■
The type definition includes a constructor. This does not have the word
public
in its header.
Enumerated type constructors are never public, because we do not create the instances. The
parameter associated with each type value is passed to this constructor.
■
The type definition includes a field,
commandString
. The constructor stores the command
string in this field.
■
A
toString
method has been used to return the text associated with a particular type value.
Search WWH ::
Custom Search