Background

Inheritance vs Composition

The ultimate showdown in Object-Oriented Design. Learn why modern development favors building over inheriting.

Inheritance Hierarchy
IS-A Relationship

account_tree Inheritance

Classes derive properties and behaviors from parent classes. Ideally used for strict hierarchical taxonomies (e.g., a "Dog" is an "Animal").

  • check_circle Great for code reuse in stable hierarchies.
  • cancel Fragile Base Class: Changes to parents break children.
  • cancel Rigid: Hard to share code between unrelated branches.
Composition Modules
HAS-A Relationship

extension Composition

Objects are built by combining smaller, independent components. This is like building with Lego blocks (e.g., a "Car" has an "Engine").

  • check_circle Flexible: Mix and match capabilities easily.
  • check_circle Loose Coupling: Components are independent and testable.
  • warning Can require more boilerplate wiring code.

The Robot Factory

Try to build a Flying & Shooting Robot using both methods.

account_tree Class Hierarchy

Select a base class chain. You can only pick one path down the tree.

Robot
smart_toy
directions_walk
flight flight
cyclone
flare
psychology
Robot
robot_factory.js
"text-blue-400">class Robot "text-yellow-600">{
  "text-yellow-400">constructor"text-gray-400">("text-gray-400">) "text-yellow-600">{ "text-red-300">this.energy = 100; "text-yellow-600">}
"text-yellow-600">}

Why Use Composition?

Feature Inheritance Composition
Relationship IS-A HAS-A
Flexibility Low. Defined at compile/creation time. High. Can change at runtime.
Coupling Tight. Child depends on Parent details. Loose. Components are independent.
Problem Fragile Base Class, Explosion of subclasses. More boilerplate code, harder to debug.

Real World Check

You are building a UI Library. You have a `Button`. You want a `Button` that has an Icon, and a `Button` that has a Loading Spinner, and a `Button` that has both.

Source data verified via Google Search. Concepts aligned with modern OOP best practices.