Aggregation & Composition
Aggregation & Composition
Aggregation & Composition
Aggregation is a specialized form of Association in which all objects have their own lifecycle.
There is a relation of ownership between 2 objects but the part object can exist even if we
delete the whole object. Let’s say we have a database in which we store information about
various departments and the teachers present in them. Now let us say, we delete the whole
department from our database. In this scenario, the teacher object should not be deleted
because the teacher may belong to some other department in the same university. We can
think of it as “has-a” relationship. In UML, Aggregation is shown with an open diamond.
Example:
Department Teacher
Composition:
Composition is again a specialized form of Aggregation. It is a strong type of Aggregation. Part
object does not have their lifecycle and if the whole object is destroyed then all part objects will
also be destroyed along with it. Let’s take an example of relationship between House and
rooms. House can contain multiple rooms. There is no independent life cycle of room and any
room cannot belong to two different houses. If we delete the house, room will automatically be
deleted. In UML, Composition is shown with a filled diamond.
Example:
House Room
class Room {
String roomType;
int length;
int width;
int height;
public Room(String roomType, int length, int height) {
this.roomType = roomType;
……..
}
}
Public class House {
private List<Room> rooms;
private int noOfRooms;
public House(int noOfRooms) {
this.rooms= new List<Room>(noOfRooms);
rooms.add(new Room(“Drawing Room”, 16, 12, 14));
rooms.add(new Room(“Living Room”, 18, 12, 14));
rooms.add(new Room(“Bed Room”, 14, 12, 14));
rooms.add(new Room(“BedRoom Room”, 12, 12, 14));
this.noOfRooms = noOfRooms;
}
}
Question 1:
You are required to design and implement an Airport simulation.
An airport facilitates various flights, each flight has a number of passengers. If airport closes,
the flights will no longer exist. But if the flight gets cancelled, the passengers in that flight will
continue to exist. Therefore, an Airport can be seen as a composition of flights and passengers,
whereas flights have an aggregation of passengers.