Inheritance creates subclasses from a superclass. The superclass passes down state through instance variables and behavior through methods; subclasses may add or override both. section 1.8
Use inheritance when a genuine is-a relationship supports a shared abstraction. A superclass can define common operations, while subclasses supply specialized behavior. Poorly chosen hierarchies, however, duplicate code, hardcode behavior, and spread changes across subclasses. section 7.3 section 7.3.1
A toy hierarchy with change leaks
A Toy superclass can require what(), play(), and sound(), with ToyCar, ModelAirplane, and TrainSet implementing them. The design duplicates play() and sound() implementations and hardcodes each toy's behavior. If play actions or sounds change, several subclasses may need modification. section 7.3.1
Inheritance also establishes a central design tradeoff:
- Template Method uses inheritance: the superclass defines an algorithm outline and subclasses implement selected steps. section 8.3
- Strategy uses composition instead: interchangeable algorithm objects remain loosely coupled to the client and can be added, removed, or updated later. section 8.3
- Compare inheritance with aggregation when behaviors vary independently; favor the relationship that avoids duplication and hardcoded decisions. section 7.3 section 7.0
Figure 7.2 This version of the application uses is-a relationships between the Toy subclasses and their superclass. Two design faults are the duplicated code, which violates the Don’t Repeat Yourself Principle, and the hardcoded play action and sound behavior of each toy.
Use the diagram to inspect the Toy superclass, its subclasses, and the duplicated or hardcoded behavior identified in the hierarchy. section 7.3.1


















