Skip to content
BENIBIX Learn

Composition vs Inheritance

Inheritance says a thing is a kind of another, like a cat is an animal. Composition says a thing has parts, like a car has an engine. Parts are easier to swap.

Development🧭 Programming Paradigms

Composition (Programming)

Building an object from the parts it holds. A car has an engine.

Composition builds an object out of other objects it holds. A Car has an Engine and has Wheels, so it keeps them as parts. Inheritance says a thing is a kind of something. Composition says a thing has something. Many teams pick composition first, because parts are easier to swap than a family tree.

Example
Jack's game gives each character a Weapon object. Swapping a sword for a bow is one line, not a new class.
Why it matters
Parts can be swapped and tested on their own. Deep chains of inheritance are much harder to change.
Full entry
Development🧭 Programming Paradigms

Inheritance

A new class that gets all of an old class's parts, then adds its own.

Inheritance lets a new class take on all the data and methods of a class that exists. Then it can add or change some. The old class is called the parent, and the new one is the child. A Cat class can get breathe from an Animal class and add its own meow. It saves writing the same code twice. Long chains of it, though, get hard to follow.

Example
Jack has an Animal class with a breathe method. His Cat class inherits it, so every cat can breathe without new code.
Why it matters
It is the most common way to share code between related classes in OOP.
Full entry

In one line

Composition (Programming)
Building an object from the parts it holds. A car has an engine.
Inheritance
A new class that gets all of an old class's parts, then adds its own.