extends, super & overriding
Share behaviour with inheritance
Lesson 11 of 20 · 11 min · Module 3: Classes and objects
Different kinds of things often share most of their behaviour. A base class holds what they have in common, and subclasses add or change only what makes them different.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Create a subclass with extends
- Call the parent constructor with super
- Override methods and reuse shared ones
The idea
class Circle extends Shape inherits every method of Shape. The subclass constructor must call super(...) before using this. A method with the same name in the subclass overrides the parent’s version, and the parent can call methods that subclasses provide.
class Animal {
constructor(name) { this.name = name; }
speak() { return this.name + " makes a sound"; }
}
class Dog extends Animal {
speak() { return this.name + " barks"; }
}
console.log(new Dog("Rex").speak());
01Write shared code once
describe is written only in Shape. Every subclass gets it for free, and fixing a bug in it fixes it for all shapes.
02super comes first
A subclass constructor must call super() before touching this, because the parent constructor creates and prepares the object.
class A { constructor() { this.kind = "A"; } }
class B extends A {
constructor() { super(); this.extra = true; }
}
console.log(new B());{"kind":"A","extra":true}03Polymorphism
describe calls this.area(). For a Circle, this is a Circle, so Circle’s area runs. Code that works with "any shape" never needs to check which kind it has.
Your turn
Shape with a name set in its constructor, an area() method that throws an Error ("not implemented"), and describe() returning e.g. "Rectangle with area 6.00". Write Rectangle(width, height) and Circle(radius) that extend Shape, pass their name to super, and override area().What the checks look for
- Rectangles and circles calculate their area
- describe uses the subclass area
- Subclasses really extend Shape
- A plain Shape cannot calculate an area
Take this with you
Inheritance shares behaviour; overriding specialises it.
Go a little further
Add a Square class that extends Rectangle and only takes one side length.