We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Inheritance

A class can inherit methods and properties from a parent class using the extends keyword:

class Titan {
  constructor(name) {
    this.name = name;
  }
}

class BeastTitan extends Titan {
  speak(msg) {
    console.log(`${this.name} says, "${msg}"`);
  }
}

const beast = new BeastTitan("Zeke");
beast.speak("You know, it's almost like throwing a baseball");
// Zeke says, "You know, it's almost like throwing a baseball"

And if we want to override a method from the parent class, we can do that too:

class Titan {
  constructor(name) {
    this.name = name;
  }

  speak() {
    // this gets overridden in the BeastTitan class
    console.log("*titan noises*");
  }
}

class BeastTitan extends Titan {
  speak() {
    console.log(`${this.name} says, "I'm the Beast Titan"`);
  }
}

const pureTitan = new Titan("Eren's mom");
pureTitan.speak();
// *titan noises*

const beast = new BeastTitan("Zeke");
beast.speak();
// Zeke says, "I'm the Beast Titan"

Assignment

Create two new classes, SMSSender and EmailSender, that extend the base Sender class. They should both override the sendMessage method.

  • SMSSender's sendMessage method should log "Sending SMS to RECIPIENT: MESSAGE" to the console.
  • EmailSender's sendMessage method should log "Sending email to RECIPIENT: MESSAGE" to the console.

RECIPIENT and MESSAGE should be replaced with the recipient field and the given message parameter.