25 Oct 2023




Beginner

The table below describes the differences between Composition, Aggregation, and Inheritance in object-oriented programming (OOP)

AspectCompositionAggregationInheritance
RelationshipStrong "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."
DependencyThe parent owns the child objects.The parent references the child objects.The child derives from the parent class.
LifespanThe 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.
FlexibilityLess 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 ReusabilityPotentially 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:

ConceptExample 1Example 2Example 3
Aggregation ExampleA 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 ExampleA "Rectangle" class inherits from a "Shape" class.A "Manager" class inherits from an "Employee" class.A "GoldenRetriever" class inherits from a "Dog" class.
Composition ExampleA 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.
object-oriented-programming
diffrence
composition
aggregation
inheritance