Aggregation Composition Program Example
Aggregation Composition Program Example
In composition, the contained object is tightly coupled to the container object. If the container
is destroyed, the contained object is also destroyed.
// Composition Example
class Engine {
void start() {
System.out.println("Engine starts");
}
}
class Car {
private Engine engine; // Composition: Car owns Engine
Car() {
engine = new Engine(); // Engine is created within Car
}
void drive() {
engine.start();
System.out.println("Car is driving");
}
}
In aggregation, the contained object is provided externally, making it loosely coupled to the
container object. The container does not manage the lifecycle of the contained object.
java
Copy code
// Aggregation Example
class Engine {
void start() {
System.out.println("Engine starts");
}
}
class Car {
private Engine engine; // Aggregation: Car uses Engine, but does not
own it
void drive() {
engine.start();
System.out.println("Car is driving");
}
}
Key Differences
1. Composition:
o The Car class owns the Engine object.
o The Engine object is created and destroyed with the Car object.
2. Aggregation:
o The Engine object is created externally and passed to the Car object.
o The lifecycle of the Engine is independent of the Car.