25 Oct 2023
Beginner
The table below describes the differences between Composition, Aggregation, and Inheritance in object-oriented programming (OOP)
| Aspect | Composition | Aggregation | Inheritance |
|---|---|---|---|
| Relationship | Strong "whole-part" relationship. | Weaker association of "whole" and "part." | Hierarchical "is-a" relationship. |
| Type of Relationship | "Part of" or "composed of." | "Has-a" or "uses." | "Is-a" or "kind of." |
| Dependency | The parent owns the child objects. | The parent references the child objects. | The child derives from the parent class. |
| Lifespan | The child objects typically have a shorter lifespan than the parent. | The child objects can exist independently of the parent. | The child objects inherit the parent's lifespan. |
| Flexibility | Less flexible; changing the parent may require changing the child classes. | More flexible; child objects can be re-associated with different parents. | More flexible; allows easy sharing of code and behavior. |
| Code Reusability | Potentially lower code reusability since child objects are tightly coupled with the parent. | Higher code reusability, as child objects can be shared among different parents. | High code reusability through method and property inheritance. |
It's important to note that these distinctions provide a general guideline, but the actual implementation and usage of these concepts can vary based on the programming language and specific design decisions.
Examples:
| Concept | Example 1 | Example 2 | Example 3 |
|---|---|---|---|
| Aggregation Example | A library aggregates books; books can be borrowed from multiple libraries. | A department aggregates employees; employees can work in multiple departments. | A "Car" class aggregates an "Engine" class, but the engine can be used in other contexts. |
| Inheritance Example | A "Rectangle" class inherits from a "Shape" class. | A "Manager" class inherits from an "Employee" class. | A "GoldenRetriever" class inherits from a "Dog" class. |
| Composition Example | A computer is composed of a CPU, RAM, and a hard drive. | A song is composed of lyrics, melody, and rhythm. | A building is composed of walls, floors, and a roof. |