Home Segments Top Top Previous Next

324: Mainline

The is-a versus has-a principle: You learned in Chapter 9 that instances mirror real-world individuals and classes mirror real-world categories. Accordingly, when you decide to implement a class, you are building a model of an aspect of the real world.

Many programmers new to object-oriented programming find it difficult to decide between implementing a new class and installing a new instance variable, because the subclass–superclass relation is easily confused with the part–whole relation.

Generally, if you find yourself using the phrase an X is a Y when describing the relation between two classes, then the first class is a subclass of the second. On the other hand, if you find yourself using X has a Y, then instances of the second class appear as parts of instances of the first class.

For example, a human is an animal. Accordingly, the is-a rule dictates that if you define a Human class, that class should be a subclass of the Animal class. Similarly, a box car is a railroad car, and the BoxCar class should be a subclass of the RailroadCar class.

On the other hand, humans have arms and legs, so the has-a rule dictates that the Human class should have Arm and Leg instance variables. Similarly, a box car has a box, and the BoxCar class therefore should have a Box instance variable.