Java Reference
In-Depth Information
9.11
Another example of inheritance with overriding
To discuss another example of a similar use of inheritance, we go back to a project from
Chapter 6: the
zuul
project. In the
world-of-zuul
game, we used a set of
Room
objects to create
a scene for a simple game. One of the exercises toward the end of the chapter suggested that
you implement a transporter room (a room that beams you to a random location in the game if
you try to enter or leave it). We revisit this exercise here, because its solution can greatly benefit
from inheritance. If you don't remember this project well, have a quick read through Chapter 6
again, or look at your own
zuul
project.
There is no single solution to this task. Many different solutions are possible and can be made
to work. Some are better than others, though. They may be more elegant, easier to read, and
easier to maintain and to extend.
Assume that we want to implement this task so that the player is automatically transported to
a random room when she tries to leave the magic transporter room. The most straightforward
solution that comes to mind first for many people is to deal with this in the
Game
class, which
implements the player's commands. One of the commands is “go,” which is implemented in
the
goRoom
method. In this method, we used the following statement as the central section
of code:
nextRoom = currentRoom.getExit(direction);
This statement retrieves from the current room the neighboring room in the direction we want
to go. To add our magic transportation, we could modify this in a form similar to the following:
if(currentRoom.getName().equals("Transporter room")) {
nextRoom = getRandomRoom();
}
else {
nextRoom = currentRoom.getExit(direction);
}
The idea here is simple: we just check whether we are in the transporter room. If we are, then
we find the next room by getting a random room (of course, we have to implement the
get-
RandomRoom
method somehow); otherwise, we just do the same as before.
While this solution works, it has several drawbacks. The first is that it is a bad idea to use text
strings, such as the room's name, to identify the room. Imagine that someone wanted to trans-
late your game into another language—say, to German. They might change the names of the
rooms—“Transporter room” becomes “Transporterraum”—and suddenly the game does not
work any more! This is a clear case of a maintainability problem.
The second solution, which is slightly better, would be to use an instance variable instead of the
room's name to identify the transporter room. Similar to this:
if(currentRoom == transporterRoom) {
nextRoom = getRandomRoom();
}
else {
nextRoom = currentRoom.getExit(direction);
}
Search WWH ::
Custom Search