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)
- How do neural networks learn? - April 17, 2018
- Artificial Neural Networks - April 17, 2018
- The Neuron in Deep Learning - April 17, 2018
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
1 2 3 4 5 |
package com.thejavageek.dp; public class Window { } |
Wall
1 2 3 4 5 6 7 8 9 10 11 |
package com.thejavageek.dp; public class Wall { private Window window; public Wall() { this.window = new Window(); } } |
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.
nice
Super
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();
}
@Override
public String toString() {
return “Inside Wall”;
}
public Window getWindow() {
return window;
}
}
public class Window {
@Override
public String toString() {
return “Inside Window”;
}
}
public class Test {
public static void main(String[] args) {
Wall w= new Wall();
System.out.println(w);
System.out.println(w.getWindow());
w=null;
System.out.println(w);
/*
* Invoking a method from a null object. will raise NullPointerException
* http://www.geeksforgeeks.org/null-pointer-exception-in-java/
*/
System.out.println(w.getWindow());
}
}