We now have a pretty good idea of what the PacMan
class would look like, with methods such as move
, chomp
, and (maybe) jump
, but what about the other actors in the game? Most notably, what about the Ghosts? If you have played Pac-Man, you consider the Ghosts to be the enemy. But if you’re thinking about how to program Pac-Man, you will notice that the Ghosts and PacMan are a lot alike. For instance, they can all move around the game board, but they can’t go through walls. In Chapter 8, “Functions and Methods,” you learned the importance of keeping your code DRY (don’t repeat yourself), but if we write a move
method for the PacMan
class and a move
method for the Ghost
class, we will be repeating ourselves. The answer to this problem is inheritance.
Inheritance means that a class can be a type of another class. As an example, I am from Nevada and am therefore a member of the Nevadan
class. All members of the Nevadan
class have certain attributes and behaviors that are specific to Nevadan
s (such as surviveRidiculousHeatWithLittleWater
), but all members of the Nevadan
class are also members of the American
class. The Nevadan
class (the subclass) inherits all the attributes and methods of the American
class (the parent class). All Nevadan
s are American
s, but not all American
s are Nevadan
s. The Texan
class, for instance, also inherits from the American
class, but from not the Nevadan
class. The concept of inheritance allows for code to be shared among different classes. Both the PacMan
class and the Ghost
class can inherit from a parent class that we’ll call MovableCharacter
. The move
method would be defined in the MovableCharacter
class and shared by both the PacMan
class and the Ghost
class (see Figure 15.5).
18.188.91.44