Understanding Composition, Aggregation & Association

Composition:

This is “Death” relationship.

In composition there is only one Owner.

Life Time of child class depends on life time of its owner. If owner is destroyed or deleted then its child will also be destroyed. That means that child is totally dependent on its owner.

E.g.

Let’s take example of Building & Doors in it.

If we destroy building then doors inside it will automatically get destroyed.

Let’s Write Code of it.

Public Class Door
{
// Some Logic
}

Public Class Building
{
Door do = new Door();
// Some Logic
}

In above code we can see that Instance of a door is created in side Building class.

i.e. If we delete Building class then Instance of Door class will also be destroyed.

Aggregation

In Aggregation there is only one Owner but child is not dependent on its Owner.

Both owner & child have different life time.

E.g.

Let’s take example of person having address i.e. each person has an address.

We can see that here Person is owner.

Here if we destroy person then address will not get destroyed as both are independent of each other, only reference of address associated with person will be destroyed.

Let’s Write Code of it.

Public Class Address
{
// some logic
}

Public Class Person
{
  Private Address add;
  Public Person (Address add)
  {
    this. add = add;
  }
}

Class Program
{
  Static Void Main(String[] args)
  {
    Address add = new Address();
    Person per = new Person(add);
  }
}

Here Main function we can see that only reference of address is passed in person class instance.

If we delete person then address will not get deleted, only its reference in person class will be deleted.

Also we can see that we are not using person any where inside address class. That means that both are independent of each other & have different life cycle.

Association

Each object in association relation are independent i.e. there is no owner in this relation.

Each object have different life time.

e.g.

Let’s take example of Employee using swipe card to enter inside office.

Public Class Employee
{
  Public void Logon (SwipeCard swp)
  {
    Sp.Swipe(this);
  }
}

Public Class SwipeCard
{
  Public Void Swipe (Employee emp)
  {
    // Some logic
  }
}

Class Program
{
  Static Void Main (String[] args)
  {
    Employee emp = new Employee ();
    SwipeCard swd = new SwipeCard();
    emp.Logon(swd);
    swd.Swipe(emp);
  }
}

In above code we can see that both employee & swipecard uses each other but there is no owner as they both can stay with each other.

This can be easily Understood from bellow table as shown in Refereed Article

Association Aggregation Composition
Owner No owner Single owner Single owner
Life time Have their own lifetime Have their own lifetime Owner’s life time
Child object Child objects all are independent Child objects belong to a single parent Child objects belong to a single parent

admin