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.



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

3 comments for “composition example

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


  2. raj gopal bhallamudi
    January 28, 2017 at 2:01 pm


  3. Raj Gopal Bhallamudi
    January 29, 2017 at 9:49 am

    Hi ,

    I modified your code for Wall and Window class. Also added a test class .

    public class Wall {

    private Window window;
    public Wall() {
    this.window = new Window();
    public String toString() {
    return “Inside Wall”;
    public Window getWindow() {
    return window;

    public class Window {
    public String toString() {
    return “Inside Window”;

    public class Test {

    public static void main(String[] args) {
    Wall w= new Wall();


    * Invoking a method from a null object. will raise NullPointerException


Leave a Reply

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