JavaScript and TypeScript course ยท Module 3: Classes and OOP

Class Inheritance (extends)

9 min read ยท
In this lesson9

In our Jurassic Park we have different types of dinosaurs that share many common traits, but also have their unique properties and behaviors. This is where class inheritance becomes extremely useful. It allows us to create hierarchies of classes, where derived (child) classes inherit properties and methods from the base (parent) class, while also adding or overriding their own functionality.

Basics of inheritance

In ES6 we use the extends keyword to inherit from a base class. Let's see how we can create a hierarchy of dinosaur classes:

// Base class for all dinosaurs
class Dinosaur {
  constructor(species, weight, diet) {
    this.species = species;
    this.weight = weight;
    this.diet = diet;
    this.health = 100;
    this.isActive = true;
  }

  makeSound() {
    return `${this.species} makes a sound!`;
  }

  feed(food) {
    this.health += 10;
    return `${this.species} was fed ${food}. Health: ${this.health}`;
  }
}

// Derived class for predators
class Carnivore extends Dinosaur {
  constructor(species, weight, dangerLevel) {
    // Calling the base class constructor
    super(species, weight, 'carnivore');
    this.dangerLevel = dangerLevel; // New property specific to predators
  }

  // Override method from base class
  makeSound() {
    return `${this.species} roars menacingly! ROAR!`;
  }

  // New method specific to predators
  hunt() {
    return `${this.species} hunts prey!`;
  }
}

// Derived class for herbivores
class Herbivore extends Dinosaur {
  constructor(species, weight, preferredPlants) {
    super(species, weight, 'herbivore');
    this.preferredPlants = preferredPlants; // Array of preferred plants
  }

  // Override method from base class
  makeSound() {
    return `${this.species} makes a gentle, low sound.`;
  }

  // New method specific to herbivores
  graze() {
    return `${this.species} peacefully nibbles vegetation.`;
  }
}

Now we can create different types of dinosaurs:

// Creating a predator instance
const trex = new Carnivore('Tyrannosaurus Rex', 8000, 'Extreme');

// Creating a herbivore instance
const triceratops = new Herbivore('Triceratops', 6000, ['ferns', 'cycads', 'conifers']);

console.log(trex.makeSound()); // "Tyrannosaurus Rex roars menacingly! ROAR!"
console.log(triceratops.makeSound()); // "Triceratops makes a gentle, low sound."

// Both classes inherit the feed method from the base class
console.log(trex.feed('meat')); // "Tyrannosaurus Rex was fed meat. Health: 110"
console.log(triceratops.feed('leaves')); // "Triceratops was fed leaves. Health: 110"

// Methods specific to derived classes
console.log(trex.hunt()); // "Tyrannosaurus Rex hunts prey!"
console.log(triceratops.graze()); // "Triceratops peacefully nibbles vegetation."

The super keyword

The super keyword has two main uses in class inheritance:

  1. Calling the superclass constructor: super(...) calls the base class constructor.
  2. Accessing superclass methods: super.method() calls a method from the base class.

Calling the superclass constructor

In the constructor of a derived class, calling super() is required before using this:

class Dinosaur {
  constructor(species) {
    this.species = species;
  }
}

class Velociraptor extends Dinosaur {
  constructor(name, speed) {
    // We must call super() first
    super('Velociraptor');

    // Now we can use this
    this.name = name;
    this.speed = speed;
  }
}

If we don't define a constructor in the derived class, JavaScript automatically creates one that calls super() with the passed arguments:

class SimpleHerbivore extends Dinosaur {
  // Constructor is implicitly defined as:
  // constructor(...args) {
  //   super(...args);
  // }
}

// Works, even without an explicit constructor
const stegosaurus = new SimpleHerbivore('Stegosaurus', 5000, 'herbivore');

Accessing superclass methods

We can use super.method() to call methods from the base class, even if they are overridden in the derived class:

class Velociraptor extends Carnivore {
  constructor(name, speed) {
    super('Velociraptor', 100, 'High');
    this.name = name;
    this.speed = speed;
  }

  makeSound() {
    // First call the original sound from the Carnivore class
    const baseSound = super.makeSound();
    // Then add the specific sound for Velociraptor
    return `${baseSound} Additionally, it makes a characteristic hiss!`;
  }

  hunt() {
    return `${super.hunt()} ${this.name} attacks at speed ${this.speed} km/h!`;
  }
}

const blue = new Velociraptor('Blue', 70);
console.log(blue.makeSound());
// "Velociraptor roars menacingly! ROAR! Additionally, it makes a characteristic hiss!"

console.log(blue.hunt());
// "Velociraptor hunts prey! Blue attacks at speed 70 km/h!"

Multi-level inheritance

Inheritance can be multi-level, meaning a class can inherit from a class that itself is a derived class:

// Base class
class Dinosaur {
  constructor(species) {
    this.species = species;
    this.extinct = true;
  }

  basicInfo() {
    return `${this.species} - extinct: ${this.extinct ? 'Yes' : 'No'}`;
  }
}

// First level of inheritance
class Theropod extends Dinosaur {
  constructor(species) {
    super(species);
    this.bipedal = true; // All theropods are bipedal
    this.carnivorous = true; // All theropods are carnivorous
  }

  locomotion() {
    return `${this.species} moves on ${this.bipedal ? 'two' : 'four'} legs.`;
  }
}

// Second level of inheritance
class Dromaeosaurid extends Theropod {
  constructor(species, feathered = true) {
    super(species);
    this.feathered = feathered; // Most dromaeosaurids had feathers
  }

  description() {
    return `${this.species} is a ${this.feathered ? 'feathered' : 'non-feathered'} dromaeosaurid.`;
  }
}

// Third level of inheritance
class Velociraptor extends Dromaeosaurid {
  constructor(name) {
    super('Velociraptor mongoliensis');
    this.name = name;
    this.dangerLevel = 'Extreme';
  }

  hunt() {
    return `${this.name} hunts in an organized group, using its intelligence and speed!`;
  }
}

// Creating instances
const delta = new Velociraptor('Delta');

// Access to methods from all levels of the hierarchy
console.log(delta.basicInfo()); // From Dinosaur
console.log(delta.locomotion()); // From Theropod
console.log(delta.description()); // From Dromaeosaurid
console.log(delta.hunt()); // From Velociraptor

Checking type and inheritance hierarchy

In JavaScript we can check if an object is an instance of a specific class using the instanceof operator:

const rex = new Carnivore('Tyrannosaurus Rex', 8000, 'Extreme');
const tric = new Herbivore('Triceratops', 6000, ['ferns', 'cycads']);
const raptor = new Velociraptor('Charlie');

console.log(rex instanceof Carnivore); // true
console.log(rex instanceof Dinosaur); // true
console.log(rex instanceof Herbivore); // false

console.log(raptor instanceof Velociraptor); // true
console.log(raptor instanceof Dromaeosaurid); // true
console.log(raptor instanceof Theropod); // true
console.log(raptor instanceof Dinosaur); // true

Limitations of inheritance

In JavaScript a class can only inherit from one base class - there is no multiple inheritance. If we need functionality from multiple different sources, we must consider other patterns such as composition or mixins.

// This is NOT allowed in JavaScript
// class ImpossibleDino extends Carnivore, SwimmingCreature {}

Mixins as an alternative to multiple inheritance

Mixins are a way to add functionality from different sources to a class:

// Mixin definitions as objects with methods
const SwimmingAbility = {
  swim() {
    return `${this.species} swims in the water!`;
  },
  dive() {
    return `${this.species} dives underwater!`;
  }
};

const FlyingAbility = {
  fly() {
    return `${this.species} soars into the air!`;
  },
  land() {
    return `${this.species} lands on the ground.`;
  }
};

// Function adding mixins to a class prototype
function applyMixins(targetClass, ...mixins) {
  mixins.forEach(mixin => {
    Object.getOwnPropertyNames(mixin).forEach(name => {
      targetClass.prototype[name] = mixin[name];
    });
  });
}

// Creating the base class
class Dinosaur {
  constructor(species) {
    this.species = species;
  }
}

// Creating classes with different abilities
class Mosasaurus extends Dinosaur {
  constructor() {
    super('Mosasaurus');
    this.habitat = 'ocean';
  }
}

class Pteranodon extends Dinosaur {
  constructor() {
    super('Pteranodon');
    this.wingspan = 7; // wingspan in meters
  }
}

class Spinosaurus extends Dinosaur {
  constructor() {
    super('Spinosaurus');
    this.hasGill = true; // gills
  }
}

// Applying mixins
applyMixins(Mosasaurus, SwimmingAbility);
applyMixins(Pteranodon, FlyingAbility);
applyMixins(Spinosaurus, SwimmingAbility, FlyingAbility); // This one can both swim and fly (hypothetically)

// Creating instances
const mosa = new Mosasaurus();
const ptero = new Pteranodon();
const spino = new Spinosaurus();

// Using abilities from mixins
console.log(mosa.swim()); // "Mosasaurus swims in the water!"
console.log(ptero.fly()); // "Pteranodon soars into the air!"
console.log(spino.swim()); // "Spinosaurus swims in the water!"
console.log(spino.fly()); // "Spinosaurus soars into the air!"

Abstract base classes

In some cases we want to create a base class that should not be instantiated by itself, but serves only as a template for derived classes. In TypeScript we can use the abstract keyword, but in plain JavaScript we can simulate this behavior:

class AbstractDinosaur {
  constructor(species) {
    // We ensure no one creates an instance of this class directly
    if (this.constructor === AbstractDinosaur) {
      throw new Error("Cannot instantiate abstract class!");
    }

    this.species = species;
  }

  // Method that child classes should implement
  makeSound() {
    throw new Error("Method makeSound() must be implemented in the child class!");
  }

  // Common method implemented in the base class
  getSpecies() {
    return this.species;
  }
}

// Derived class correctly implements the abstract method
class Diplodocus extends AbstractDinosaur {
  constructor() {
    super('Diplodocus');
  }

  makeSound() {
    return "Deep, powerful humming.";
  }
}

// Let's try to create instances
try {
  const abstractDino = new AbstractDinosaur('Generic'); // Will throw error
} catch (error) {
  console.log(error.message); // "Cannot instantiate abstract class!"
}

const diplo = new Diplodocus();
console.log(diplo.makeSound()); // "Deep, powerful humming."
console.log(diplo.getSpecies()); // "Diplodocus"

// Derived class without implementation of abstract method
class IncompleteImplementation extends AbstractDinosaur {
  constructor() {
    super('Incomplete');
  }

  // Missing makeSound() implementation
}

const incomplete = new IncompleteImplementation();
try {
  incomplete.makeSound(); // Will throw error
} catch (error) {
  console.log(error.message); // "Method makeSound() must be implemented in the child class!"
}

Inheritance in TypeScript

In TypeScript, inheritance is more explicit, thanks to static typing and additional features such as abstract classes and access modifiers:

// Abstract base class in TypeScript
abstract class Dinosaur {
  protected species: string;
  protected health: number;
  public isActive: boolean;

  constructor(species: string) {
    this.species = species;
    this.health = 100;
    this.isActive = true;
  }

  // Abstract method that child classes must implement
  abstract makeSound(): string;

  // Implemented method that child classes inherit
  public getHealth(): number {
    return this.health;
  }

  // Protected method that child classes can use, but is not accessible from outside
  protected heal(amount: number): void {
    this.health += amount;
    if (this.health > 100) this.health = 100;
  }
}

class TRex extends Dinosaur {
  private attackPower: number;

  constructor(name: string, attackPower: number) {
    super('Tyrannosaurus Rex');
    this.attackPower = attackPower;
  }

  // Implementation of abstract method
  makeSound(): string {
    return "POWERFUL ROAR!";
  }

  // Additional method specific to TRex
  attack(): string {
    return `T-Rex attacks with force ${this.attackPower}!`;
  }

  // Using the protected method from the base class
  feed(): void {
    this.heal(20);
    console.log(`T-Rex was fed and recovered health. Current health: ${this.getHealth()}`);
  }
}

Summary

Class inheritance in ES6 is a powerful mechanism that allows us to create object hierarchies and share code between them. In our Jurassic Park, we used inheritance to:

  1. Create a common base class Dinosaur with basic functionality
  2. Divide dinosaurs into subclasses such as Carnivore and Herbivore
  3. Create specific species as child classes
  4. Add various abilities and behaviors using mixins
  5. Use abstract base classes to ensure consistency of implementation

Remember a few important things:

  • In JavaScript you can only inherit from one base class
  • Calling super() is required in the constructor of a derived class before using this
  • You can use super.method() to call a method from the base class
  • The instanceof operator lets you check if an object is an instance of a specific class or its base class
  • Mixins are an alternative to multiple inheritance

Class inheritance is one of the basic concepts of object-oriented programming and gives us powerful tools to structure code in a logical and maintainable way.

Code for this lesson: index.js
// Class inheritance - extends in Jurassic Park
console.log("=== ES6 class inheritance - extends ===\n");

// Base class Animal
class Animal {
  constructor(species, weight) {
    this.species = species;
    this.weight = weight;
    this.isAlive = true;
  }

  breathe() {
    return `${this.species} breathes`;
  }

  move() {
    return `${this.species} is moving`;
  }

  getInfo() {
    return `${this.species} (${this.weight}kg)`;
  }
}

// Carnivore class inherits from Animal
class Carnivore extends Animal {
  constructor(species, weight, huntingStyle) {
    super(species, weight); // calling parent constructor
    this.diet = "carnivore";
    this.huntingStyle = huntingStyle;
  }

  // Method override (override)
  move() {
    return `${this.species} is sneaking quietly...`;
  }

  // New method
  hunt(prey) {
    return `${this.species} hunts ${prey} (${this.huntingStyle})`;
  }

  roar() {
    return `${this.species}: ROAAAAR!`;
  }
}

// Herbivore class inherits from Animal
class Herbivore extends Animal {
  constructor(species, weight, defenseType, herdSize) {
    super(species, weight);
    this.diet = "herbivore";
    this.defenseType = defenseType;
    this.herdSize = herdSize;
  }

  move() {
    return `Herd of ${this.species} (${this.herdSize} individuals) migrates`;
  }

  graze() {
    return `${this.species} grazes peacefully`;
  }

  defend() {
    return `${this.species} defends itself: ${this.defenseType}!`;
  }
}

// Creating instances
const rex = new Carnivore("T-Rex", 8000, "ambush");
const raptor = new Carnivore("Velociraptor", 15, "pack attack");
const trike = new Herbivore("Triceratops", 6000, "sharp horns", 12);
const stego = new Herbivore("Stegosaurus", 5000, "tail spikes", 8);

console.log("--- Carnivores ---");
console.log(rex.getInfo());       // method from Animal
console.log(rex.breathe());       // method from Animal
console.log(rex.move());          // overridden method
console.log(rex.hunt("Gallimimus"));
console.log(rex.roar());

console.log("\n--- Herbivores ---");
console.log(trike.getInfo());
console.log(trike.move());        // overridden method
console.log(trike.graze());
console.log(trike.defend());

console.log("\n--- instanceof ---");
console.log(`Is Rex an Animal? ${rex instanceof Animal}`);
console.log(`Is Rex a Carnivore? ${rex instanceof Carnivore}`);
console.log(`Is Trike a Herbivore? ${trike instanceof Herbivore}`);
console.log(`Is Trike a Carnivore? ${trike instanceof Carnivore}`);

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the purpose of super() in a child class constructor?

  2. 2. What does the extends keyword mean in a class declaration?

Hands-on tasks in the game

  • Code editor

    Create a dinosaur class hierarchy with inheritance

  • Vertical ordering

    Arrange the elements of an ES6 class method:

  1. QuestionThe super Keyword
  2. QuestionInheritance with extends
  3. Coding taskClass Inheritance (extends)
  4. Put in orderClass Method Syntax

Useful articles