0% found this document useful (0 votes)
3 views

Aggregation Composition Program Example

Uploaded by

right2abhinavrs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Aggregation Composition Program Example

Uploaded by

right2abhinavrs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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() {
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");
}
}

public class CompositionExample {


public static void main(String[] args) {
Car car = new Car();
car.drive();
}
}

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() {
System.out.println("Engine starts");
}
}

class Car {
private Engine engine; // Aggregation: Car uses Engine, but does not
own it

Car(Engine engine) { // Engine is passed to Car


this.engine = engine;
}

void drive() {
engine.start();
System.out.println("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
car.drive();
}
}

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.

You might also like