Join 36000+ teachers and students using TTIO.
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:
The two types of Association relationships are Aggregation and Composition.
An association relationship between two classes is a “has a” relationship. For example:
Car
has an Engine
and a Wheel
Person
has a Leg
and an Arm
Book
has Pages
This usually represents when there are two classes, ClassA
and ClassB
, and either:
ClassA
contains ClassB
as an attribute, orClassB
are constructed inside ClassA
With an aggregation, the child can exist independently of the parent. Consider now a Car
and an Engine ...
the Engine
doesn’t need to be destroyed when the Car
is destroyed. This is the key idea. The engine component can be retained!
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 exists
UML distinguishes between composition and aggregation. (These are often synonymous terms.)
www.teachyourselfpython.com