Advanced Topic 46 of 54 Programming Fundamentals
Composition over Inheritance
Preferring building objects from parts to deep class hierarchies.
How it works
Instead of inheriting behavior from a parent class, an object holds other objects and delegates work to them. This lets behavior be swapped at runtime, avoids rigid class trees and combines capabilities freely. Strategy, decorator and dependency-injection patterns are built from composition, and it reflects a has-a relationship.
Step-by-step walkthrough
- Instead of Car extending Engine, a Car has an Engine.
- It also has wheels and a radio as parts.
- Parts can be swapped, for example an electric engine.
- Behavior is combined by delegating to parts.
- This avoids deep, rigid class trees.
Where it is used
A Car has an Engine rather than being a kind of Engine, a game entity has components for movement and rendering, and a logger composes a formatter and a writer. Composition is common in modern frameworks and entity-component systems.
Common pitfall
Composition adds boilerplate for delegation and more objects to wire together. Inheritance is still fine for genuine is-a relations with stable hierarchies. Avoid deciding by habit: ask whether the relationship is an identity or a role, and whether behavior needs to change at runtime.
Where it fits in the course
Composition over Inheritance is topic 46 of 54 in Programming Fundamentals, rated Advanced. It follows Interfaces and Abstract Classes. The next topic is Functional Programming.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Composition over Inheritance?
Where do people use Composition over Inheritance?
What is the most common mistake with Composition over Inheritance?
What should I learn before this topic?
How can I practice it?
Is Composition over Inheritance hard to learn?
How long does it take to learn Composition over Inheritance?
Which topics are related to Composition over Inheritance?
What should I study after Composition over Inheritance?
Related topics
- Interfaces and Abstract Classes (Programming Fundamentals)
- Functional Programming (Programming Fundamentals)
- Abstraction (Programming Fundamentals)
- Pure Functions (Programming Fundamentals)