What is Composition and how it maps into a Java class
A Composition is a tight Association and denotes "whole-part" relationship.So when an object is destroyed then all its constituents are also destroyed, these 'parts' have no meaning/sense in their lone existence from their 'whole'.
The best example of Composition is a 'Human body' which is composed of two legs,two hands,two eyes,two ears and so on.During the lifetime of a human being,all organs make sense being part of whole,but once a human being is dead most of these parts are also dead,unless some of his body parts are not medically reused.
Now come to map composition to Java world, the best example is garbage collection feature of the language.While garbage collecting objects, whole has the responsibility of preventing all its parts being garbage collected by holding some references to them.
It is the responsibility of whole to protect references to its parts not being exposed to outside world.The only way to have true composition in Java is to never let references to internal objects escape their parent's scope.
An example of Inner class as shown in the following code snippet may give you an idea how to implement Composition in Java.
public class Human
{
public Human()
{
Brain brain = new Brain();
}
private class Brain
{
....
....
}
}
The best example of Composition is a 'Human body' which is composed of two legs,two hands,two eyes,two ears and so on.During the lifetime of a human being,all organs make sense being part of whole,but once a human being is dead most of these parts are also dead,unless some of his body parts are not medically reused.
Now come to map composition to Java world, the best example is garbage collection feature of the language.While garbage collecting objects, whole has the responsibility of preventing all its parts being garbage collected by holding some references to them.
It is the responsibility of whole to protect references to its parts not being exposed to outside world.The only way to have true composition in Java is to never let references to internal objects escape their parent's scope.
An example of Inner class as shown in the following code snippet may give you an idea how to implement Composition in Java.
public class Human
{
public Human()
{
Brain brain = new Brain();
}
private class Brain
{
....
....
}
}