Composition Relationship is a relationship between a whole object and one of its integrated parts.
In short, it can be say to be a whole-part relationship; it is also commonly referred to as has a relationship.
Let's use an apartment as an example. An apartment is composed of at least a living room, bedroom,
kitchen, and a bathroom.
As the word "composed" stated, an apartment has a composition relationship
with each of its parts.
The composition relationship between the apartment and one of its parts shows that the lifetime of these
two objects (the apartment and one of its parts)
involved are tied together. For example, the lifetime of the
apartment and its living room are tied together, because an apartment must have a living room.
Let's see a composition relationship looks in the UML diagram. We will use the two objects as mentioned
above, the apartment and its living room.
As you can see, the composition relationship is shown using a solid line that connects the living room class to
the apartment class;
the diamond shape is pointing at the apartment class. We call the whole class (apartment)
as the source, and the part class (living room) as the target.
Let's see how the UML diagram above would look like in code:
As you see in the code, we see the package declaration follow by the class definition. Inside the class definition,
we have the instance variable then follow by the constructor definition. Inside the constructor, we created a new
instance of the LivingRoom and assigned it to the instance variable.
The composition relationship is appropriate to be used in the program if the program has a whole object that
must include a part in it.
For example, if you are creating a program called "Window with a Ball", then of
course a ball must be present in the window when you run the program.