Home Segments Index Top Previous Next

290: Mainline

The is-a versus has-a principle: You learned in Chapter 11 that instances mirror real-world individuals and classes mirror read-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, X and Y, 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, Y, appear as parts of instances of the first class, X.

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 arms and legs instance variables. Similarly, a box car has a box, and the BoxCar class therefore should have a box instance variable.