Inheritance: Building Class Hierarchies
Building hierarchies of code to promote reuse and flexible system design.
About This Topic
Inheritance is one of the most powerful--and most frequently misused--features of object-oriented programming. At its core, inheritance allows a new class to acquire the properties and behaviors of an existing class, enabling code reuse and creating logical hierarchies that mirror real-world relationships. In Java or Python, for example, a Dog class might inherit from an Animal class, automatically gaining common fields like name and age while adding dog-specific behavior like fetch().
In the US K-12 CS curriculum at the 11th-grade level, students learning inheritance should understand not just how it works syntactically but when to use it. The classic guidance is to apply inheritance when the relationship between classes is genuinely 'is-a': a Dog is an Animal, a Savings Account is a Bank Account. When the relationship is better described as 'has-a'--a Car has an Engine--composition is usually the better design. Conflating these leads to fragile hierarchies that are difficult to maintain.
Active learning works well for inheritance because class hierarchy design involves genuine judgment calls. Design exercises where students propose hierarchies and then critique each other's choices--asking 'does this actually model the domain accurately?'--develop the kind of critical thinking that distinguishes good software design from mechanical code writing.
Key Questions
- Explain how inheritance allows new classes to acquire properties and behaviors from existing ones.
- Analyze the benefits of code reuse and reduced redundancy through inheritance.
- Design a class hierarchy for a given problem domain, identifying parent and child classes.
Learning Objectives
- Explain how inheritance allows a child class to acquire properties and behaviors from a parent class.
- Analyze the benefits of code reuse and reduced redundancy when designing class hierarchies.
- Design a class hierarchy for a given problem domain, identifying appropriate parent and child classes.
- Critique proposed class hierarchies for accuracy in modeling relationships and potential design flaws.
Before You Start
Why: Students must understand the fundamental concepts of classes as blueprints and objects as instances before they can grasp how one class can build upon another.
Why: Inheritance involves acquiring both behaviors (methods) and properties (attributes), so students need a solid understanding of these core class components.
Key Vocabulary
| Inheritance | A mechanism where a new class (child or subclass) derives properties and behaviors from an existing class (parent or superclass). |
| Class Hierarchy | An arrangement of classes where parent classes are at a higher level and child classes are at a lower level, forming a tree-like structure. |
| Code Reuse | The practice of using existing code in new programs, often facilitated by inheritance, to avoid rewriting common functionality. |
| Is-a Relationship | A type of relationship where a child class is a specialized version of its parent class, e.g., a 'Car' is a 'Vehicle'. |
| Has-a Relationship | A relationship where one class contains an instance of another class, e.g., a 'Car' has an 'Engine'. This is typically modeled with composition, not inheritance. |
Watch Out for These Misconceptions
Common MisconceptionInheritance is always better than writing the same code twice.
What to Teach Instead
Inheritance creates a strong coupling between parent and child classes. Changes to the parent can break children unexpectedly. Composition--where a class holds a reference to another class rather than extending it--is often more flexible. The rule of thumb is: use inheritance for genuine 'is-a' relationships, composition for 'has-a'.
Common MisconceptionA child class always has access to all parent class members.
What to Teach Instead
Private members of a parent class are not accessible in child classes. Protected members are accessible in child classes but not to outside code. Understanding visibility modifiers in the context of inheritance is essential for designing class hierarchies that work as intended.
Common MisconceptionDeep inheritance hierarchies are a sign of good design.
What to Teach Instead
Deep hierarchies (more than two or three levels) are generally a warning sign. They become difficult to trace, fragile when parent classes change, and hard for new developers to understand. Most well-designed OOP systems prefer shallow hierarchies and composition over deep inheritance chains.
Active Learning Ideas
See all activitiesDesign Challenge: Build a Zoo Class Hierarchy
Groups design a class hierarchy for a zoo management system. They identify parent classes, child classes, inherited attributes and methods, and any behaviors that need to be overridden. Groups draw their hierarchy on paper or a whiteboard, then present it to the class and field questions about their design decisions.
Gallery Walk: Inheritance or Composition?
Post six design scenarios around the room (e.g., Vehicle/Car/Truck, Employee/Manager, Shape/Circle, Library item/Book/DVD). Students rotate with sticky notes, marking each scenario 'Inheritance' or 'Composition' and writing a one-sentence reason. Debrief on contested cases to explore where reasonable designers disagree.
Code Tracing: What Does This Class Inherit?
Provide a three-level inheritance hierarchy in code with five method calls. Students trace through each call individually, determining whether the method comes from the parent or child class and what the output will be before running the code. Compare predictions with actual output, then discuss surprising cases.
Real-World Connections
- Software engineers developing video games use inheritance to create a hierarchy of game characters. A base 'Character' class might define common attributes like health and position, while child classes like 'PlayerCharacter' and 'Enemy' inherit these and add unique abilities or behaviors.
- Financial institutions design banking systems using class hierarchies. A base 'Account' class could hold common features like account number and balance, with subclasses like 'SavingsAccount' and 'CheckingAccount' inheriting these and adding specific rules for interest or overdrafts.
Assessment Ideas
Present students with a scenario, for example, designing classes for different types of musical instruments. Ask them to identify one potential parent class and two child classes, listing one inherited property and one unique behavior for each child.
Students individually design a simple class hierarchy for a given domain (e.g., shapes, vehicles). They then swap designs with a partner and answer: 'Does the 'is-a' relationship make sense for all parent-child connections? Are there any obvious redundancies that could be moved to a parent class?'
Pose the question: 'When is inheritance the right tool for code organization, and when might composition be a better choice?' Facilitate a class discussion where students share examples and justify their reasoning, referencing the 'is-a' versus 'has-a' distinction.
Frequently Asked Questions
What is the difference between inheritance and composition in OOP?
What does 'super' do in Java or Python inheritance?
Can a class inherit from multiple parent classes?
How does active learning improve students' understanding of inheritance?
More in Object-Oriented Programming
Introduction to OOP Concepts
Students will learn the core principles of Object-Oriented Programming (OOP) and its benefits.
2 methodologies
Classes and Objects
Defining custom data types (classes) and creating instances (objects) with attributes and behaviors.
2 methodologies
Abstraction and Encapsulation
Hiding complexity by grouping data and behavior into manageable objects.
2 methodologies
Polymorphism: Many Forms
Enabling objects of different classes to be treated as objects of a common type.
2 methodologies
Interfaces and Abstract Classes
Defining contracts for classes and providing partial implementations for common behavior.
2 methodologies
Error Handling and Exceptions
Implementing robust code that gracefully handles unexpected situations and errors.
2 methodologies