Inheritance vs. Composition
Reuse behavior cleanly with extends and super, and learn when composition (has-a) beats deep inheritance trees.
What you'll learn
- Extend a base class using extends and call super() in subclasses
- Recognize the difference between is-a (inheritance) and has-a (composition)
- Prefer composition when combining flexible, independent behaviors
Inheritance allows a subclass to reuse fields and methods from a parent class (AdminUser extends User). Composition builds complex objects by combining smaller, focused objects (Car has an Engine).
Favor Composition Over Deep Inheritance
Deep inheritance hierarchies (4+ levels) become fragile: changing one method in the root class can accidentally break distant subclasses. Use inheritance for true is-a relationships, and composition for has-a capabilities.
Fill-in-the-Blank Exercise
Subclassing with extends & super
Make Mentor inherit from User and forward name to the parent constructor.
class Mentor User {
constructor(name, specialty) {
(name);
this.specialty = specialty;
}
}Try It Yourself (Live OOP Playground)
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. Which relationship is best modeled with composition rather than inheritance?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.