Deepen your understanding of object relationships by exploring key differences between association, aggregation, and composition in object-oriented design. This quiz is crafted to strengthen your grasp of these foundational concepts with practical examples and clear explanations.
Which scenario best illustrates a simple association relationship in object-oriented programming?
Explanation: In association, objects have a loose relationship where they can exist independently; for example, teachers and courses are related but do not depend on each other's existence. The car and engine example is closer to composition, as the engine typically cannot exist without the car. Books existing only within a library suggests composition, not association. Destruction of a house leading to the destruction of its rooms is another characteristic of composition, not association.
Which option correctly describes aggregation using a real-life analogy?
Explanation: Aggregation represents a 'has-a' relationship with independent lifecycles; departments can exist outside the context of a university. The heart and person example is composition since the heart cannot function independently. Computer and RAM that cannot be reused implies composition, not aggregation. Inheritance relationships, like parent and child here implying dependency, are not examples of aggregation.
In which scenario does composition most accurately take place?
Explanation: Composition means that the child object’s lifecycle is tied to the parent; if the house is destroyed, its rooms cease to exist, fitting composition. Books borrowed from a library and residents in a city can exist independently, which demonstrates association. Car wheels reused elsewhere indicate aggregation, as wheels can exist independently from the car.
What is a key difference between aggregation and composition in terms of object lifecycle?
Explanation: Aggregation allows the child to exist independently of the parent, whereas composition tightly couples the lifecycle so the child is destroyed with the parent. Saying composition allows the child to outlive the parent is incorrect; the opposite is true. The notion of aggregation requiring dependency is incorrect, and requiring only one parent applies more strictly to composition, not both.
In standard UML diagrams, how is a composition relationship typically represented?
Explanation: A filled (black) diamond in UML denotes composition, indicating strong ownership and parent-child lifecycle dependency. A plain line illustrates association, not composition. An empty diamond represents aggregation, showing a weaker relationship. A solid arrow is typically used for inheritance or dependency, not for composition.