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:
Library
and Book
relationship. A library
has books, but a book can exist outside of a library.House
and Room
relationship. A house has
rooms, and a room cannot exist without the house.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.
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:
canvas
object on which the shapes can be drawnshape
object from which the drawing is composedComposition is enabled by having attributes in the container class that can hold other objects.
Here, we have:
The addObject()
method enables new objects to be added to the objects
attribute which is a list.
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.
The reDraw()
method loops through the objects
list and uses the object's
own draw()
method to draw the object onto the canvas
.
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