In Object-Oriented Programming (OOP), both aggregation and composition are types of associations that represent relationships between objects. However, they differ in terms of the strength and nature of the relationship:

Aggregation

  • Definition: Aggregation is a "has-a" relationship where one object (the whole) contains other objects (the parts), but the parts can exist independently of the whole.
  • Example: A Library and Book relationship. A library has books, but a book can exist outside of a library.
  • Lifespan: The lifespan of the parts is independent of the whole. If the whole is destroyed, the parts can still exist.

Composition

  • Definition: Composition is a stronger "has-a" relationship where one object (the whole) contains other objects (the parts), and the parts cannot exist independently of the whole.
  • Example: A House and Room relationship. A house has rooms, and a room cannot exist without the house.
  • Lifespan: The lifespan of the parts is dependent on the whole. If the whole is destroyed, the parts are also destroyed.

Drawing and Shapes

In this tutorial, we will use Composition since the shape object cannot exist outside of the drawing

This relationship is represented on a class diagram by a filled-in diamond at the end of the line.

logo

Composition in JavaScript

Composition

Here, we have a class for a drawing. The drawing is not a shape but it has shapes in it.

The drawing needs to be made up of:

  • a canvas object on which the shapes can be drawn
  • a set of shape object from which the drawing is composed

How Do We Compose?

Composition is enabled by having attributes in the container class that can hold other objects.

Here, we have:

  • canvas object: this is a HTML DOM element
  • objects list: this is the container for all the objects on the drawing

Adding Objects into the Drawing

The addObject() method enables new objects to be added to the objects attribute which is a list.

Removing Objects into the Drawing

The clear() method empties the objects attribute which is a list. It then uses the clearCanvas() method of the the canvas object to clear the canvas of any shapes that have been drawn.

Redrawing Objects

The reDraw() method loops through the objects list and uses the object's own draw() method to draw the object onto the canvas.

Defining a Class in PYTHON





This is a development site to gather together teaching materials for AQA A Level Computer Science. It will be changing and being remodelled throughout this year.

No data is stored on the site but cookies are used to enable the website to function properly.

© 2025 Jay Patel - Dixons Sixth Form Academy, Bradford

Contact: jpatel@dixons6a.com