Step 1: Composition 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() {
[Link]("Engine starts");
}
}
class Car {
private Engine engine; // Composition: Car owns Engine
Car() {
engine = new Engine(); // Engine is created within Car
}
void drive() {
[Link]();
[Link]("Car is driving");
}
}
public class CompositionExample {
public static void main(String[] args) {
Car car = new Car();
[Link]();
}
}
Step 2: Convert Composition to Aggregation
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() {
[Link]("Engine starts");
}
}
class Car {
private Engine engine; // Aggregation: Car uses Engine, but does not
own it
Car(Engine engine) { // Engine is passed to Car
[Link] = engine;
}
void drive() {
[Link]();
[Link]("Car is driving");
}
}
public class AggregationExample {
public static void main(String[] args) {
Engine engine = new Engine(); // Engine is created externally
Car car = new Car(engine); // Engine is passed to Car
[Link]();
}
}
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.