But enums serve a greater purpose in OOP, especially in Java: creating advanced structures for multiple, nearly identical classes, in a consolidated way.
Check out this example: Command.java. Ignore the two custom imports at the top, for now. Let's focus on what's going on in this code.
public enum Command { // defines commands available in the user interface
Note that in this .java file, which is code for the Command class, never once is the word "class" mentioned, except for in a comment. That's interesting...The reason is because this public enum essentially serves as a fork for
Command.java, turning it into, when it compiles, one class for each element in the enum. Basically, every element in a class's enum behaves as if it were a pre-generated instance of the class in which it's used. In this case, each element is an instance of the Command class.There are six enumerated elements in Command:
COUNT, EXIT, HELP, NEW, PRINT, and SPEED. Note that each element has its own series of three String[]s. Let's scroll down to the constructor to find out what these are for...Command(String[] variants, String[] text, String[] aliases)Ah, it looks like these are something called "variants," "text," and "aliases." Right above this constructor they are commented for their purpose. And if we look at each enumerated element, they seem to fit this description. The first two are used as part of the
{
this.variants = variants;
this.text = text;
this.aliases = aliases;
}
HELP command, and the third provides an array of synonyms, which the user can also use to invoke that particular command (ex. a user could type exit, quit, or bye into the command line, to invoke the EXIT command).After the three
String[]s, it looks like each element has its own definition of a doCommand() function. Note that further down in the class definition there is this line of code:
abstract public boolean doCommand(String[] line, Map<String,Vehicle> items);
...which makes it impossible for any element not to have its own definition of this command. That makes sense, since each command needs to know how to do itself. (Don't snicker.)Next time, we'll get into how
No comments:
Post a Comment