Composition and Aggregation

Composition and Aggregation

In this tutorial, we are going to discuss composition and aggregation in java. Composition and aggregation are both forms of association between classes in object-oriented programming, but they represent different relationships in terms of ownership and lifespan.

Composition and Aggregation
Composition

In the case of composition, whenever a container object is destroyed, all contained objects will be destroyed automatically. i.e., without an existing container object, there is no chance of an existing contained object, i.e., container and contained objects having a strong association.

E.g

University is composed of several departments. Whenever you are closing university automatically, all departments will be closed. The relationship between university object and department object is the strong association which is nothing but composition.

Aggregation

Whenever a container object is destroyed, there is no guaranty of the destruction of contained objects, i.e., without an existing container object, there may be a chance of an existing contained object. i.e., container objects just maintain references of contained objects. This relationship is called weak association, which is nothing but Aggregation.

E.g

Several professors will work in the department. Whenever we are closing the department still there may be a chance of existing professors. The relationship between department and professor is called weak association, which is nothing but Aggregation.

In summary, composition implies ownership and a stronger relationship between the whole and its parts, while aggregation implies a looser relationship where the contained objects can exist independently. Both composition and aggregation are important concepts in designing object-oriented systems and modeling relationships between classes.

That’s all about Composition and Aggregation in Java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!

Composition and Aggregation
Scroll to top