Class Inheritance

A subclass can inherit properties and methods from a parent class using extends. The super keyword is used to call the parent class constructor or methods.

Basic Inheritance (extends and super())

When a class extends another class, it automatically gains access to its properties and methods.

class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a noise`;
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name); // Calls Animal's constructor
  }
  speak() {
    return `${this.name} barks`;
  }
}

const dog = new Dog("Buddy");
console.log(dog.speak()); // Buddy barks

Calling Parent Methods Using super.methodName()

A subclass can still use parent class methods via super.methodName().

class Parent {
  greet() {
    return "Hello from Parent";
  }
}

class Child extends Parent {
  greet() {
    return super.greet() + " and Child";
  }
}

const child = new Child();
console.log(child.greet()); // Hello from Parent and Child

Overriding Methods & Using super Inside a Method

A subclass can override a method but still use the parent method inside.

class Animal {
  constructor(public name: string) {}

  speak() {
    return `${this.name} makes a noise.`;
  }
}

class Dog extends Animal {
  speak() {
    return super.speak() + " But actually, it barks.";
  }
}

const dog = new Dog("Charlie");
console.log(dog.speak());
// Charlie makes a noise. But actually, it barks.

super with Getters & Setters

If the parent class has getters/setters, the child class can override them and use super.