Some Objects can be similar. They share common logic but they might vary slightly from each other. For example, all shapes in a 2D drawing will have an outline, line colour, fill colour etc.
However, they will be drawn differently because they have different characterisitcs. They will also have different calculations for determining their perimeters and areas.
For example, a square is a 2D shape that has to have all sides the same and joined at 90 degree angles. A Circle is different still but has all other characteristics of a shape.
So how do we reuse the common logic and extract the unique logic into a separate class? One way to achieve this is inheritance.
It means that you derive a child class by using a base class as a parent. This way, we form a hierarchy.
The child or derived class reuses all attributes and methods of the parent class - the common part - and can implement its own unique part.
So, Inhertiance is a relationship that can be described as "is a" relationship:
In this tutorial, we will use Inheritance with the parent class of shape
and the child class of the particular shapes that we will define.
This relationship is represented on a class diagram by a open triangle at the end of the line and pints from child to parent.
In JS, the key word extends
is used to show that the new class is based on the parent class.
You can see that here where rectangle extends shape
.
To ensure that the base class
is activated, all programming languages use a line of code that activates it. In JS this is the method super
Here it provides all of the parameters for shape
. Following that the extended
attributes are set. This ensures that all attributes and methods from shape
are passed on to rectangle
.
If an inherited method needs adapting, it can be redefined in the child
class. This is called overriding. In other words, the child class overrides the method from the parent class.
In this case, there is an abstract method called draw()
that needs redefining now it has context. This uses the jCanvas method drawRect()
to do this.
If a new method needs adding, it can be defined in the child
class.
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