1

I have googled the difference between composition and aggregation in Java. I know the fact that the child class cannot live without the parent in the composition if the parent class got removed. However, I couldn't find anything about what would happen if a child class got removed in the composition and aggregation, will the parent class still exist? Since the child class is an important part forming the parent class in the composition, should I assume the parent will die if the child class got removed?

For example, we got human as a parent and heart as a child. If the heart class got removed, human should be removed. because human can't live without heart

randomguy
  • 79
  • 5

1 Answers1

1

In composition the parent is independent of the child while the child is dependent on the parent. The parent can create and destroy children and the created child cannot exist without the parent. For example a building has apartments, if the building gets destroyed then the apartments will cease to exist, but if you destroy an apartment in the building then the building will remain. Even if you destroy all the apartments the building will be a building without apartments. It is a "owns" relationship, the parent owns the child and the child cannot exist without the parent, but the child does not own the parent.

In aggregation parent and child are independent of each other, and each can exist without the other, it is a "has-a" relation. For example a room has a chair in it, if you break the chair the room will still exist, and if you take the chair out and destroy the room the chair will still exist.

Bashi
  • 174
  • 6