25 Oct 2023
Aggregation in object-oriented programming (OOP) is a type of object relationship in which one object "has-a" another object. This means that the parent object contains a reference to the child object, but the child object can still exist independently.
Aggregation is often used to model real-world relationships, such as the relationship between a car and its engine. A car has-an engine, but the engine can still exist independently of the car.
Another example of aggregation is the relationship between a department and its employees. A department has-a collection of employees, but the employees can still exist independently of the department.
Aggregation is different from inheritance in that inheritance is a "is-a" relationship. This means that the child object is a specialized type of the parent object. For example, a car is-a type of vehicle.
Aggregation is also different from composition in that composition is a stronger type of relationship than aggregation. In composition, the child object cannot exist independently of the parent object. For example, a wheel is a part-of a car, and a wheel cannot exist without a car.
Class Car:
// Car class has a reference to an Engine and a list of Wheels
Engine engine
List<Wheel> wheels
// Constructor to initialize the car with an engine and wheels
Constructor Car(Engine engine, List<Wheel> wheels):
this.engine = engine
this.wheels = wheels
Class Engine:
// Engine class with attributes and methods
Attribute type
Method start():
// Start the engine
// Implementation details
Class Wheel:
// Wheel class with attributes and methods
Attribute size
Method rotate():
// Rotate the wheel
// Implementation details
// Creating an instance of an Engine
Engine carEngine = new Engine("V8")
// Creating a list of Wheel instances
List<Wheel> carWheels = [new Wheel(18), new Wheel(18), new Wheel(18), new Wheel(18)]
// Creating a Car instance using aggregation
Car myCar = new Car(carEngine, carWheels)
// Accessing and using the aggregated components
myCar.engine.start()
for each wheel in myCar.wheels:
wheel.rotate()
In this example, the Car class contains an Engine and a list of Wheel objects, forming an aggregation relationship. The Engine and Wheel objects can exist independently of the Car and can be reused in other contexts. This demonstrates the concept of aggregation in object-oriented programming.