Aggregation and Composition are basically the concepts about how to manage objects.
Aggregation
Aggregation uses loose coupling, which means that it does not hold the actual object in the class. Instead, the object is being passed via getter or setter function. It gives the benefit that when the object of the parent class dies then the child class object remains intact.
class House {
private Table table;
public void setTable(Table table){
this.table = table
}
public Table getTable(){
return this.table;
}
}
public class main(String[] args){
Table table = new Table();
// this house' table is set externally and will not be deleted
// upon deleting this House object
House house = new House();
house.setTable(table);
}
Composition
Composition uses tight coupling, which means that it holds the object. An instance variable is created and the object is stored in it. Whenever the object of the parent class removed/deleted then the child class object will also be deleted.
class Human {
// This heart will be deleted and nowhere to access once its
// human gets deleted
private Heart heart = new Heart();
}
public class main(String[] args){
// this human's heart is set internally and will be deleted
// upon deleting this Human object
Human human = new Human();
}
Top comments (0)