Aggregation vs. Composition in Object Oriented Programming

In Object Oriented Programming, there are many different types of relationships which can exist between two or more classes. The most common two types are:
- Inheritance — an “is a” relationship
- Association — a “has a” relationship
This blog is going to do a deep dive into the two types of Association relationships — Aggregation and Composition.
What is an Association relationship?
An association relationship between two classes is a “has a” relationship. For example:
- A
Carhas anEngineand aWheel - A
Personhas aLegand anArm - A
BookhasPages
This usually represents when there are two classes, ClassA and ClassB, and either:
ClassAcontainsClassBas an attribute, or- Instances of
ClassBare constructed insideClassA
What’s the difference between Aggregation and Composition?
There are two sub-types of Association relationships — Aggregation and Composition. What’s the difference between these two?
Composition
Composition implies that the contained class cannot exist independently of the container. If the container is destroyed, the child is also destroyed.
Take for example a Page and a Book. The Page cannot exist without the Book, because the book is composed of Pages. If the Book is destroyed, the Page is also destroyed.
In code, this usually refers to the child instance being created inside the container class:
class Book:
def __init__(self):
page1 = Page('This is content for page 1')
page2 = Page('This is content for page 2')
self.pages = [page1, page2]
class Page:
def __init__(self, content):
self.content = contentbook = Book() # If I destroy this Book instance,
# the Page instances are also destroyedAggregation
With an aggregation, the child can exist independently of the parent.
So thinking of a Car and an Engine, the Engine doesn’t need to be destroyed when the Car is destroyed.
class Car:
def __init__(self, engine):
self.engine = engine
class Engine:
def __init__(self):
passengine = Engine()
car = Car(engine) # If I destroy this Car instance,
# the Engine instance still existsHow are these represented a UML diagram?
In a UML diagram, both Aggregation and Composition are represented with a diamond arrow between the classes. The diamond end goes on the side of the container.
- Aggregation uses an open diamond
- Composition uses a closed diamond
Here’s an example:

Hope this helped!
