|
Sometimes you need the functionality of other classes in your class. But your class is not exactly the kind-of those classes. In other words your class does not have IS-A relationship which these classes. For instance, A Car class needs Engine class’s functionality. But a car is-not-an engine or an engine –is-not-a-car. Therefore you cannot (and should not) have Engine class as its subclass or superclass of Car. Then how would the Car class use the functionality of Engine class? The Car and engine share different relationship as an engine is a part of Car. In fact a car can be made up of various such parts, engine, tires, headlights, windshield and so on. Figure 11.4 shows the composition of Car with many parts.
![]() |
Figure 11.4 Car is composed of several parts
Figure shows a Car and its parts. Now you can say that, ‘a car has-a battery, engine, headlights, tires..’. Since the whole car is composed of parts, it shares a part-whole relationship with its parts. This relationship is called as composition. It is usually identified by the term HAS-A and hence is also called as HAS-A relationship. You can easily spot composition when you look for any of the following phrases in problem definition.
"has a"
"is made up of"
"is composed of"
Composition often passes the 'life and death' test. The parts have the same life as the whole. For instance, a windshield is part-of Car. Windshield exists as long as Car object exist. The moment Car object’s life ends, all its part’s life is also over.