Inheritance
In Object-Oriented Programming, Inheritance allows a class to inherit the methods and properties of another parent class. This prevents code duplication and creates a logical hierarchy of data models.
The extends Keyword
You establish an inheritance relationship using the extends keyword.
class Titan {
constructor(name) {
this.name = name;
}
}
// BeastTitan inherits everything from Titan
class BeastTitan extends Titan {
speak(msg) {
console.log(`${this.name} says, "${msg}"`);
}
}
// 'name' is handled by the parent Titan constructor
const beast = new BeastTitan("Zeke");
beast.speak("I'm throwing a baseball");
// Output: Zeke says, "I'm throwing a baseball"
Overriding Methods
If a child class defines a method with the exact same name as a method in its parent class, the child’s method overrides the parent’s method.
class Titan {
constructor(name) {
this.name = name;
}
speak() {
console.log("*titan noises*");
}
}
class BeastTitan extends Titan {
// This completely replaces the parent speak() method for BeastTitans
speak() {
console.log(`${this.name} says, "I'm the Beast Titan"`);
}
}
const pureTitan = new Titan("Eren's mom");
pureTitan.speak(); // Output: *titan noises*
const beast = new BeastTitan("Zeke");
beast.speak(); // Output: Zeke says, "I'm the Beast Titan"
Practical Example
A messaging platform might have a base Sender class that handles the core network logic, while specific SMSSender and EmailSender subclasses extend it to override how the message string is formatted before sending.