Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Although inheritance is a common practice in object-oriented programming, it’s not the only way to build OOP projects. Composition is more appropriate in some cases. Composition says that an object is composed of other objects, rather than descending from other objects. The best way to decide when to use inheritance or composition is to follow the “is a/has a” rule.
Consider how to add tires to the car example. You might be able to use inheritance (“is a”), but composition (“has a”) is likely better. A car “is a” vehicle, meaning inheritance will work well, but tires don’t fit the “is a” vehicle, or car, or truck model. However, a car (or truck) “has a” set of tires, making this model suited to composition. In a real-world scenario, this might be particularly useful in an expanded version of our vehicle metaphor. For example, land vehicles typically have tires, but water vehicles usually don’t.