Composition vs. Inheritance
Compare and contrast composition and inheritance as design principles for code reuse and relationship modeling.
About This Topic
Composition and inheritance serve as key principles in object-oriented programming for code reuse and modeling relationships between classes. Inheritance establishes 'is-a' relationships, where a subclass extends a superclass to inherit its properties and behaviors. Composition creates 'has-a' relationships, where one class contains instances of another as components. Students compare these approaches to understand when each promotes flexible, maintainable designs.
In the Ontario Grade 11 Computer Science curriculum, this topic aligns with standards CS.HS.D.1 and CS.HS.P.4 by developing skills in design analysis and problem-solving. Students analyze advantages like composition's support for runtime flexibility and avoidance of inheritance hierarchies that can become rigid or tightly coupled. They practice justifying choices for scenarios such as building vehicle systems or user interfaces, fostering critical thinking about software architecture.
Active learning shines here because students can code prototypes, refactor designs, and test outcomes in real time. Pair programming to swap between inheritance and composition reveals maintainability differences concretely, while group critiques build consensus on best practices. These methods turn abstract principles into practical expertise.
Key Questions
- Differentiate between 'is-a' and 'has-a' relationships in object-oriented design.
- Analyze the advantages of composition over inheritance in terms of flexibility and maintainability.
- Justify the choice between composition and inheritance for a given design problem.
Learning Objectives
- Compare and contrast the 'is-a' and 'has-a' relationships represented by inheritance and composition, respectively.
- Analyze the advantages of using composition over inheritance for enhancing code flexibility and maintainability in object-oriented designs.
- Justify the selection of either composition or inheritance for a given software design problem, citing specific reasons.
- Critique existing code examples to identify instances where composition could improve upon an inheritance-based design.
Before You Start
Why: Students need a foundational understanding of classes, objects, attributes, and methods to grasp how inheritance and composition facilitate code organization and reuse.
Why: Prior exposure to basic object relationships, such as association, is helpful for understanding the nuances of 'is-a' versus 'has-a' connections.
Key Vocabulary
| Inheritance | A mechanism where a new class (subclass or derived class) acquires properties and behaviors from an existing class (superclass or base class). It models an 'is-a' relationship. |
| Composition | A design principle where a class contains instances of other classes as members, allowing it to use their functionality. It models a 'has-a' relationship. |
| 'is-a' relationship | A type of relationship in object-oriented design where one class is a specialized version of another class, inheriting its characteristics. For example, a 'Car' is-a 'Vehicle'. |
| 'has-a' relationship | A type of relationship in object-oriented design where one class contains an instance of another class as a component, utilizing its features. For example, a 'Car' has-a 'Engine'. |
| Code Reuse | The practice of using existing code in new programs to reduce development time and effort, achieved through mechanisms like inheritance and composition. |
Watch Out for These Misconceptions
Common MisconceptionInheritance is always preferable for code reuse.
What to Teach Instead
Composition often provides better reuse through delegation without superclass dependencies. Active refactoring exercises let students break inheritance chains and see reduced coupling firsthand. Peer reviews reinforce when 'favor composition over inheritance' applies.
Common Misconception'Is-a' and 'has-a' relationships are interchangeable.
What to Teach Instead
'Is-a' implies substitutability, while 'has-a' supports independent lifecycles. Drawing UML diagrams in pairs clarifies distinctions, and testing substitutability reveals errors in misapplied inheritance.
Common MisconceptionDeep inheritance hierarchies improve design.
What to Teach Instead
They risk fragility and poor maintainability. Group coding sprints to flatten hierarchies demonstrate faster adaptations, helping students prioritize shallow designs.
Active Learning Ideas
See all activitiesPair Programming: Vehicle Design Challenge
Pairs sketch 'is-a' and 'has-a' relationships for vehicles, engines, and wheels. They code both inheritance and composition versions, then run tests to swap engine types. Discuss which approach allows easier changes.
Small Groups: Refactoring Relay
Groups receive inheritance-based code for a library system. Each member refactors one class to composition, passes to the next, and notes changes in flexibility. Debrief as a class on outcomes.
Whole Class: Design Debate
Divide class into teams: one defends inheritance, the other composition for a game character system. Teams code minimal examples, present pros/cons with live demos, and vote on best fit.
Individual: Choice Justification
Students select a personal project, implement using one principle, then refactor to the other. Write a short report justifying the final choice based on maintainability and flexibility.
Real-World Connections
- Software engineers developing game engines often use composition to build complex game entities. For instance, a 'Player' character might 'have-a' 'MovementComponent', 'HealthComponent', and 'InventoryComponent', allowing for flexible combinations of abilities without deep inheritance chains.
- UI/UX designers and developers for applications like Adobe Photoshop or Figma utilize composition extensively. A 'Button' widget might 'have-a' 'LabelComponent', 'StyleComponent', and 'EventHandlingComponent', enabling designers to assemble diverse interactive elements from reusable parts.
Assessment Ideas
Present students with two class diagrams: one using inheritance (e.g., 'Dog' inherits from 'Animal') and another using composition (e.g., 'Car' has an 'Engine'). Ask students to write one sentence for each diagram explaining the relationship modeled and identify which uses 'is-a' and which uses 'has-a'.
Pose the scenario: 'Imagine you are designing a system for different types of electronic devices (e.g., smartphone, tablet, laptop). Discuss with a partner whether you would primarily use inheritance or composition to model the shared functionalities like 'power on/off' and 'display screen'. Justify your choice.'
Ask students to write down one situation where inheritance would be a suitable design choice and one situation where composition would be preferable. For each, briefly explain why their chosen principle fits the scenario.
Frequently Asked Questions
How do I explain 'is-a' vs 'has-a' relationships?
When should students prefer composition over inheritance?
What active learning strategies work best for teaching composition vs inheritance?
How does this topic connect to real software development?
More in Object-Oriented Programming and Design
Introduction to Object-Oriented Programming (OOP)
Students will understand the fundamental concepts of OOP: objects, classes, and instances, and their role in modeling real-world entities.
2 methodologies
Encapsulation and Data Privacy
Implement access modifiers to protect internal object states and ensure data integrity.
2 methodologies
Class Hierarchies and Inheritance
Design systems using parent and child classes to model real-world relationships and reduce code redundancy.
2 methodologies
Polymorphism and Interfaces
Utilize interfaces and abstract classes to define common behaviors across different object types.
2 methodologies
Abstract Classes and Methods
Students will learn to use abstract classes to define common interfaces for a group of related classes, enforcing specific behaviors.
2 methodologies
Introduction to Design Patterns
Students will be introduced to common software design patterns (e.g., Singleton, Factory) as reusable solutions to recurring problems.
2 methodologies