Difficulty: Easy
Correct Answer: Composition
Explanation:
Introduction / Context:
Classes often collaborate by containing other objects. This design choice models real-world “has-a” relationships and is a cornerstone of object composition over inheritance.
Given Data / Assumptions:
Concept / Approach:
Composition (also aggregation, depending on ownership) models has-a. For example, a Car has an Engine. This differs from inheritance (is-a), where a SportsCar is a kind of Car, and from encapsulation, which is about access control and hiding implementation details.
Step-by-Step Solution:
1) Define: class Car { Engine engine; } → composition.2) Ownership: if Car controls the lifetime of Engine, that is composition (stronger than aggregation).3) Interactions: Car methods may call Engine methods to implement behavior.4) Contrast: class SportsCar : public Car {}; → inheritance (is-a), not composition.
Verification / Alternative check:
UML shows composition with a filled diamond and aggregation with a hollow diamond; both are “has-a,” but composition implies strong ownership.
Why Other Options Are Wrong:
Encapsulation: information hiding inside a class boundary.Inheritance: is-a relationship, not has-a.Abstraction: focusing on relevant features, omitting details.Polymorphism: treating different types uniformly via a common interface.
Common Pitfalls:
Overusing inheritance where composition would be simpler and safer; prefer composition to reduce coupling and increase flexibility.
Final Answer:
Composition
Discussion & Comments