Composition and Its Implementation

What is composition?

Complex objects are typically constructed by assembling smaller and simpler components. For instance, a car is composed of wheels, doors, an engine, and a frame, while a computer comprises a CPU, a hard disk, a motherboard, and several other components. Similarly, the human body comprises various parts, such as the head, legs, arms, etc. The process of creating a more intricate object by combining simpler ones is referred to as composition.

Object composition can generally be considered to establish a HAS-A or WHOLE-PART relationship between two objects. For instance, a car HAS-A tire(s), a computer HAS-A motherboard, and a human HAS-A leg(s). The complex object involved in the relationship is commonly referred to as the whole or the parent, while the simpler object is often known as the part, child, or component.

Why composition?

Object composition proves to be beneficial as it enables us to construct intricate classes by aggregating simpler, more manageable components. This results in decreased complexity and enables faster and more error-free coding because we can reuse the code of individual composed unit (created, implemented, and tested separately) that has already been tested and verified to function properly.

Real-life example

To exemplify composition relationships, let’s consider the connection between a car and its engine. A car’s engine is an essential part of its body. It can’t function without it. A part in a composition relationship can only belong to one object at a time. Once an engine is installed in a car, it can’t simultaneously power another vehicle.

In a composition relationship, the object controls the existence of its parts. Typically, the part is created with the object’s creation and is destroyed when the object is no longer in use. Therefore, the user does not need to manage the part’s lifetime. For instance, when a car is manufactured, the engine is created and installed within the vehicle. When the car is eventually scrapped, the engine is also scrapped. This aspect of composition is sometimes called a death relationship.

Furthermore, the part is unaware of the whole’s existence. The engine works independently and is unaware of the larger structure in which it is placed. We call this a unidirectional relationship since the car recognizes the engine, but the engine doesn’t recognize the car.

Let’s draw the class diagram:

Get hands-on with 1200+ tech skills courses.