Preview lessons, content and tests

Computer Science & Programming solved. All in one platform.

1. To trial the platform and take tests, please take a few seconds to SIGN UP and SET UP FREE.

2. Searching for something specific? See our text overview of all tests. Scroll right for levels, and lists.

3. Student and Teacher User Guides |  Schemes of Work |   Real Teacher use Videos |


Join 36000+ teachers and students using TTIO.

Composition

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 — “has a” relationship

 

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?

 

Definition and example

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 destroyed

Suggested Video

Additional Reading

https://realpython.com/inheritance-composition-python/

www.teachyourselfpython.com