Aggregation vs Composition

    Aggregation and Composition are very closely related terms where a novice gets confused and some examples are of good debate too.

    Observe the code.

    class Test
    {
      public void display() {  System.out.println("Hello 1");  }
    }
    class Demo
    {
      public static void main(String args[])
      {
        Test t1 = new Test();
        t1.display();
      }
    }
    

    We say, class Demo has the object t1 of Test class. Or say, Demo "has-a" object of Test. This is known as "has-a" relationship and is known as composition in Java. This, we know earlier in detail in "Composition – “has-a” Relationship". Other name of composition is aggregation.

    Between composition and aggregation, a small difference exists. It is simply if Demo can exist without Test, it is known as aggregation and if Demo cannot exist without Test object, it is known as composition.

    After this introduction of Aggregation vs Composition, let us go with good examples to know better.

    1. Heart and human body. Heart exists within a human body. It is an association between two. They are dependent. Can a heart exist without human body? Simply no. It is known as composition. That is, a child cannot exist without parent. Heart is completely controlled human body (organs).

    2. Library and book. It is also an association. Can a book exist without library? Yes, it can; I have got only one book in my hand, it is possible. That is, delete (remove) the library, still book can exist. It is an aggregation. But a library cannot exist without books. So here, you should consider the direction also. From book to library it is aggregation but from library to book it is composition. Dependency matters.

    In UML diagrams we represent aggregation as


    Aggregation vs Composition

    and composition as

    Aggregation vs Composition

    A restricted aggregation is composition. The literal meaning of aggregation is collection of things together. An aggregation is nothing but a collection.

    In brief, in aggregation association, child can exist independently without the parent. In composition association, a child cannot exist without parent. Child is completely controlled by parent.

    Suppose take another example, say car. A car HAS-A engine, which states in car object we will define engine object.

    Composition is a STRONGER relationship whereas Aggregation is a WEAKER relationship. Composition depicts dependency between objects but Aggregation depicts related objects can exist independently.

    After understanding Aggregation vs Composition, Now check yourself with some examples.

6 thoughts on “Aggregation vs Composition”

  1. Hi Sir, I am a great fan of your explanation… Please help me on this question.. In which place i need to use Aggregation and Composition ? and which one we are using now a days.

Leave a Comment

Your email address will not be published.