Inheritance allows a class to inherit properties and methods from another class. The derived class (child class) inherits the behavior of the base class (parent class) and can also add its own behavior or override inherited methods.

Example 1: Basic Inheritance

class Animal {
  move(distanceInMeters: number = 0) {
    console.log(`Animal moved ${distanceInMeters}m.`);
  }
}
 
class Dog extends Animal {
  bark() {
    console.log("Woof! Woof!");
  }
}
 
const dog = new Dog();
dog.bark();            // Dog's own method
dog.move(10);          // Inherited method from Animal
dog.bark();            // Dog's own method
  • The Dog class extends the Animal class, inheriting its move method.
  • The Dog class also adds its own bark method.

Example 2: Constructor Inheritance and Method Overriding

class Animal {
  name: string;
 
  constructor(theName: string) {
    this.name = theName;
  }
 
  move(distanceInMeters: number = 0) {
    console.log(`${this.name} moved ${distanceInMeters}m.`);
  }
}
 
class Snake extends Animal {
  constructor(name: string) {
    super(name);  // Call the parent class constructor
  }
 
  move(distanceInMeters = 5) {
    console.log("Slithering...");
    super.move(distanceInMeters);  // Call the base class move method
  }
}
 
class Horse extends Animal {
  constructor(name: string) {
    super(name);  // Call the parent class constructor
  }
 
  move(distanceInMeters = 45) {
    console.log("Galloping...");
    super.move(distanceInMeters);  // Call the base class move method
  }
}
 
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
 
sam.move();         // Snake's move method (overridden)
tom.move(34);       // Horse's move method (overridden)
  • Constructor Inheritance: The Snake and Horse classes call the parent class constructor (super(name)) to initialize the name property.
  • Method Overriding: Both Snake and Horse override the move method from Animal.
    • The Snake class customizes the move method with “Slithering…” and then calls super.move() to retain the base behavior.
    • The Horse class customizes the move method with “Galloping…” and similarly calls super.move() to retain the base behavior.

Key Points:

  1. Inheritance allows a child class to inherit properties and methods from a parent class using the extends keyword.
  2. A child class can override methods from the parent class to provide its own implementation.
  3. The super keyword is used to call the parent class’s methods or constructor.