difference between aggregation and composition in java with example
Aggregation and Composition are both forms of association in Java, representing relationships between classes. The key difference lies in the strength of the relationship and the lifecycle of the objects involved.
Aggregation:
Aggregation represents a “has-a” relationship where one class contains an object of another class, but the contained object can exist independently of the container. In aggregation, the objects have a weaker relationship. If the container object is destroyed, the contained object can continue to exist.
Example of Aggregation:
Consider the relationship between a University
class and a Department
class. A University
has multiple Department
objects. If the university is closed, departments can still exist and be associated with another university.
/*
* Author: Zameer Ali
* */
class Department {
// Department properties and methods
}
class University {
private List<Department> departments;
public University(List<Department> departments) {
this.departments = departments;
}
// University properties and methods
}
In this example, University
aggregates Department
objects. Even if the university is closed, departments can still exist independently.
Composition:
Composition also represents a “has-a” relationship, but it’s a stronger form of association. In composition, one class contains an object of another class, and the contained object cannot exist or be meaningful without the container object. If the container object is destroyed, all the contained objects are also destroyed.
Example of Composition:
Consider the relationship between a House
class and a Room
class. A House
has multiple Room
objects. If the House
is demolished, all the Room
objects inside it become meaningless.
/*
* Author: Zameer Ali
* */
class Room {
// Room properties and methods
}
class House {
private List<Room> rooms;
public House(List<Room> rooms) {
this.rooms = rooms;
}
// House properties and methods
}
In this example, House
composes Room
objects. If the House
object is destroyed (demolished), all the Room
objects inside it lose their meaning.
Key Differences:
- Existence: In aggregation, the contained object can exist independently of the container. In composition, the contained object cannot exist without the container.
- Ownership: Aggregation implies a weaker relationship where objects are related, but not in an ownership relationship. Composition implies a stronger relationship where one object owns the other.
- Lifecycle: Aggregated objects have an independent lifecycle. Composed objects have a lifecycle dependent on the container object.
Remember, the choice between aggregation and composition depends on the nature of the relationship between the classes and the requirements of the system being modeled.