Skip to content
Computer Science · Grade 11 · Object-Oriented Programming and Design · Term 2

Composition vs. Inheritance

Compare and contrast composition and inheritance as design principles for code reuse and relationship modeling.

Ontario Curriculum ExpectationsCS.HS.D.1CS.HS.P.4

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

  1. Differentiate between 'is-a' and 'has-a' relationships in object-oriented design.
  2. Analyze the advantages of composition over inheritance in terms of flexibility and maintainability.
  3. 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

Introduction to Object-Oriented Programming

Why: Students need a foundational understanding of classes, objects, attributes, and methods to grasp how inheritance and composition facilitate code organization and reuse.

Class Relationships in OOP

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

InheritanceA 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.
CompositionA 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' relationshipA 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' relationshipA 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 ReuseThe 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 activities

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

Quick Check

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'.

Discussion Prompt

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.'

Exit Ticket

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?
Use real-world analogies: a car 'is-a' vehicle (inheritance) but 'has-a' engine (composition). Have students list examples, draw diagrams, and code snippets. This builds intuition before diving into code, ensuring they distinguish substitutability from containment. Testing edge cases solidifies understanding.
When should students prefer composition over inheritance?
Choose composition for flexibility in swapping components or avoiding tight coupling, like UI elements or plugins. Inheritance suits true subtype behaviors, such as shapes in graphics. Guide students through case studies where refactoring inheritance to composition cuts modification ripple effects, emphasizing the principle 'composition over inheritance'.
What active learning strategies work best for teaching composition vs inheritance?
Pair programming challenges and refactoring relays engage students directly. They code both approaches for the same problem, measure change impacts, and debate trade-offs. Whole-class demos of failures, like fragile base classes, make principles memorable. These methods develop design judgment through iteration and collaboration.
How does this topic connect to real software development?
Industry favors composition for maintainable, testable code in frameworks like Spring or game engines. Students analyze open-source examples, justifying redesigns. This prepares them for portfolios and interviews, where explaining design choices demonstrates professional skills.