Composition Example

Use composition by placing one object inside another to build complex behavior.

PythonIntermediate
Python
# Program to demonstrate composition

class Engine:
    def start(self):
        print("Engine started")


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

    def drive(self):
        self.engine.start()
        print("Car is moving")


c = Car()
c.drive()

Output

Engine started
Car is moving

Car is composed of an Engine object; it delegates the 'start' behavior to Engine instead of inheriting from it.