11.2. Polymorphic Video GameSuppose we design a video game that manipulates objects of many different types, including objects of classes Martian, Venutian, Plutonian, SpaceShip and LaserBeam. Imagine that each class inherits from the common base class called SpaceObject, which contains method draw. Each derived class implements this method in a manner appropriate to that class. A screen-manager program maintains a collection (e.g., a SpaceObject array) of references to objects of the various classes. To refresh the screen, the screen manager periodically sends each object the same messagenamely, draw. However, each object responds in a unique way. For example, a Martian object might draw itself in red with the appropriate number of antennae. A SpaceShip object might draw itself as a bright silver flying saucer. A LaserBeam object might draw itself as a bright red beam across the screen. The same message (in this case, draw) sent to a variety of objects has "many forms" of results. A screen manager might use polymorphism to facilitate adding new classes to a system with minimal modifications to the system's code. Suppose that we want to add Mercurian objects to our video game. To do so, we must build a class Mercurian that inherits from SpaceObject and provides its own draw method implementation. When objects of class Mercurian appear in the SpaceObject collection, the screen manager code invokes method draw, exactly as it does for the other objects in the collection, regardless of their types. So the new Mercurian class simply "plugs right in" without any modification of the screen manager code by the programmer. Thus, without modifying the system (other than to build new classes and modify the code that creates new objects), programmers can use polymorphism to include types that were not envisioned when the system was created. With polymorphism, calls to methods of the same method name, signature and return type can be used to cause different actions to occur, depending on the type of objects on which the method is invoked. This gives you tremendous expressive capability, as you will soon see. Software Engineering Observation 11.1
|