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:
There are two sub-types of Association relationships — Aggregation and Composition. What’s the difference between these two?
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
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:
page1 = Page('This is content for page 1')
page2 = Page('This is content for page 2')
self.pages = [page1, page2]
def __init__(self, content):
self.content = contentbook = Book() # If I destroy this Book instance,
# the Page instances are also destroyed