You are here

"Has-a" or "Composition"

26 July, 2019 - 09:51
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at http://cnx.org/contents/402b20ad-c01f-45f1-9743-05eadb1f710e@37.6

"Has-a" or "composition" (sometimes referred to as an "associative") relationships capture the notion that one object has a distinct and persistent communication relationship with another object. for instance, we can say a car "has-a" motor. The car and the motor are not related in a hierarchal manner, but instead we need to be able to express that this pair of objects has a particular working relationship. The car gives gas to the motor and the motor will propel the car along. Compositional relationships can be one-way, where one object can, in a persistent manner, talk to (i.e. call methods of) a second object but the second object cannot, in a persistent manner, talk back to the first object. Compositional relationships can also be two-way, where both objects can talk to each other in a persistent manner.

media/image3.png
Figure 1.3 UML Class Diagram Showing Composition 
The above diagram shows the "has-a" relationships between the Car, Motor and Wheel classes 
Note: Composition ("has-a") lines are represented by solid lines with open arrowheads. The arrow points from the owner ("composite") to the ownee ("composee"). Think "a composite has a composee". The number at the arrowhead tells how many composees there are, e.g. 1, 2, etc. "*" means an limited number, so "0...*” means zero or more and "1...*" means at least one.

The emphasis made above with regards to persistent communication is deliberate and important. It is indeed possible for an object to communicate with another object in a non-persistent manner. Such non-persistent communication is generally not thought of as a compositional relationship, but rather as a dependency relationship where the action of one object depends on that of another. An object can tell a second object that it (the second object) needs to talk to a specific, perhaps third object. The second object does not know with whom it will be communicating until the first object tells it. The second object may not "remember" the object it is supposed to communicate with for any length of time after the communication was accomplished and the second object merely waits for the first object to tell it with whom to communicate next. This non-persistent communication is normally established by simply passing the third target object as an input parameter to the method call made on the second object by the first. Note that the third object could actually be the frst object, creating a non-persistent two-way communication from an initially one-way communication.