composition example

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

In previous post we have seen an example of aggregation. Here we will deal with another association type i.e. composition. The article will provide a daily life simple composition example to understand the concept better

Composition Example

Two classes have composition relationship when one class completely depends upon other class and it does not have existence outside the owning class. When owning class is destroyed, then the owned class also gets destroyed.

For our composition example article, consider following scenario

  • A Wall class which contains Window object i.e. a Wall HAS-A Window
  • The Window cannot exist without a wall, how could it exist?
  • So whenever a wall is demolished, window also does not exist.

So our composition example has following classes.

Window

 Wall

Things to notice in composition example

  • Wall class has reference to Window class by declaring an instance member  private Window window;
  • Wall has a no argument constructor in which a Window object is created.
  • So whenever you create a Wall using new Wall(),  automatically a new Window()  is created and assigned to window instance member
  • In this scenario we cannot set window from outside. It simply cannot exist outside the Wall
  • Now if we make wall = null;  then window object is also removed, because it does not have a outside reference.
  • So the existence of Window depends completely upon existence of Wall.

So this composition example explains that composition is a strong association. The owned object cannot exist when the owner does not exist.

 

Share Button

1 comment for “composition example

  1. sethu
    May 7, 2015 at 5:05 pm

    nice

Leave a Reply

Your email address will not be published. Required fields are marked *