Composition

Introduction to Software Engineering (CSSE 1001)

Author

Paul Vrbik

Published

March 13, 2025

Composition (Has-a)

There is an alternative to inheritance called composition. When an object (say Person) includes another object inside of itself (say Animal) this forms an has-a relationship.

class Person():
     def __init__(self, name: str, pet: Animal) -> str:
         self._pet = pet  # Person has-a pet.

The has-a relationship also applies to all the attributes of an object. That is, Cat has-a name and has-a age.

class Engine():
     def read_odometer() -> str:
         return self._odometer
    
class Car:
     def __init__(self):
         self._engine = Engine()   # Car has-a Engine
     
     def read_odometer() -> str:
         return self._engine.read_odometer()
    
car = Car()
car.read_odomter()