Java Reference
In-Depth Information
public Room getExit(String direction)
{
return findRandomRoom();
}
/*
* Choose a random room.
* @return A random room.
*/
private Room findRandomRoom()
{
...
// implementation omitted
}
}
The elegance of this solution lies in the fact that no change at all is needed in either the origi-
nal
Game
or
Room
classes! We can simply add this class to the existing game, and the
goRoom
method will continue to work as it is. Adding the creation of a
TransporterRoom
to the setup
of the floor plan is (almost) enough to make it work. Note, too, that the new class does not need a
flag to indicate its special nature—its very type and distinctive behavior supply that information.
Because
TransporterRoom
is a subclass of
Room
, it can be used everywhere a
Room
object is
expected. Thus, it can be used as a neighboring room for another room or be held in the
Game
object as the current room.
What we have left out, of course, is the implementation of the
findRandomRoom
method.
In reality, this is probably better done in a separate class (say
RoomRandomizer
) than in the
TransporterRoom
class itself. We leave this open as an exercise for the reader.
Exercise 9.8
Implement a transporter room with inheritance in your version of the
zuul
project.
Exercise 9.9
Discuss how inheritance could be used in the
zuul
project to implement a
player and a monster class.
Exercise 9.10
Could (or should) inheritance be used to create an inheritance relationship
(super-, sub-, or sibling class) between a character in the game and an item?
9.12
Summary
When we deal with classes with subclasses and polymorphic variables, we have to distinguish
between the static and dynamic type of a variable. The static type is the declared type, while the
dynamic type is the type of the object currently stored in the variable.
Type checking is done by the compiler using the static type, whereas at runtime method lookup
uses the dynamic type. This enables us to create very flexible structures by overriding methods.
Even when using a supertype variable to make a method call, overriding enables us to ensure
that specialized methods are invoked for every particular subtype. This ensures that objects of
different classes can react distinctly to the same method call.
Search WWH ::
Custom Search