To represent inheritance between classes, we can use a class diagram showing which classes inherit from which other classes. This may make the terms ‘superclass’ and ‘subclass’ easier to remember, as super- indicates the class above, while sub- indicates the class below. Some people like to compare these diagrams to family trees.
In the diagram, each class is represented by a rectangle. An arrow points towards the class from which something is inherited.
Looking at a class diagram can also help us to understand polymorphism. If a class inherits from another class, it can also be considered to be an object of that class. For example,
Enemy inherits from
Enemy is a
In week 1 we used the
gpiozero library to create an
LED object in code to represent a physical LED.
We can see in the diagram below that the class
LED is a subclass of
OutputDevice. This means that
LED is an
OutputDevice – it inherits the properties of a generic
OutputDevice and adds some specialised methods of its own.
Buzzer is also a subclass of
OutputDevice, but it has different functionality. If you look into the documentation, you will find that
LED has a
blink() method, whereas
Buzzer has a
beep() method. Both
Buzzer inherit the same
off() methods from
© CC BY-SA 4.0