# Composition (Programming)

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

**Field:** Software Development  
**Category:** Programming Paradigms  
**Also known as:** Object Composition, Composition over Inheritance, Has-A Relationship

## Think of it like

It is like building a toy car from blocks. You snap an engine block and four wheel blocks together.

## Definition

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.

## Example code

```python
class Engine:
    def start(self):
        return "vroom"

class Car:
    def __init__(self):
        self.engine = Engine()

print(Car().engine.start())
# vroom
```

The car holds an engine and uses it. It is not a kind of engine.

## Why it matters

Parts can be swapped and tested on their own. Deep chains of inheritance are much harder to change.

## Common mistake

Using inheritance when the words are has a, not is a. A car is not a kind of engine.

## Three principles

- **Has a, not is a.** The object holds its parts.
- **Easy to swap.** Change one part, keep the rest.
- **Before inheritance.** Reach for it first.

## Related terms

- [Inheritance](https://learn.benibix.com/term/development/inheritance)
- [Object (Programming)](https://learn.benibix.com/term/development/object)
- [Class](https://learn.benibix.com/term/development/class)
- [Polymorphism](https://learn.benibix.com/term/development/polymorphism)
- [Design Pattern](https://learn.benibix.com/term/development/design-pattern)

## Told apart from

- [Composition vs Inheritance](https://learn.benibix.com/compare/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.

![Three panels. Struct: one box named Point holding x and y together. Union type: a value that is either a string or a number, shown as two doors with or between them. Composition: a Car box that holds an Engine box and four Wheel boxes inside it.](https://learn.benibix.com/diagrams/dev7-data-shapes.svg)

---

Source: https://learn.benibix.com/term/development/composition
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
