25 Oct 2023
Composition in OOP is a technique for creating new objects by combining existing objects. It is often described as a "has-a" relationship. For example, a car has-a engine, tires, and steering wheel. Each of these components is its own object, and the car is composed of these objects.
Composition is a powerful tool for code reuse and modularity. It allows us to create complex objects by combining simple objects. This can make our code easier to understand and maintain.
Simple example of composition in OOP using a "Car" class composed of various components like an "Engine" and "Wheels." Here's a pseudocode representation of this composition:
class Engine:
// Properties and methods of the Engine class
method start():
// Logic to start the engine
method stop():
// Logic to stop the engine
class Wheel:
// Properties and methods of the Wheel class
method rotate():
// Logic to make the wheel rotate
class Car:
// Properties
engine: Engine
wheels: list of Wheel
// Constructor
constructor(engine: Engine, numberOfWheels: integer):
this.engine = engine
this.wheels = new list of Wheel
for i from 1 to numberOfWheels:
this.wheels.append(new Wheel)
// Methods
method start():
engine.start()
for each wheel in wheels:
wheel.rotate()
method stop():
engine.stop()
for each wheel in wheels:
// Stop the wheel (stop rotating)
In this pseudocode:
- We have three classes:
Engine,Wheel, andCar. - The
EngineandWheelclasses represent the components of a car. - The
Carclass is composed of anEngineand a list ofWheelobjects. - The
Carclass's constructor allows you to specify the engine and the number of wheels when creating a car instance. - The
start()andstop()methods of theCarclass use composition to interact with the engine and wheels to start and stop the car.
This pseudocode demonstrates how composition allows you to create a complex object (the "Car") by combining simpler objects (the "Engine" and multiple "Wheels") to represent a real-world relationship.