All academies

Inheritance

extends, super(), method overriding, and constructor chaining.

18 minLevel 9 of 20

extends and is-a

Inheritance models true specialization: a Dog is-an Animal. Subclasses inherit members and can override methods.

Use the Inheritance Visualizer to inspect the hierarchy.

Basic extends
class Animal {
  constructor(public name: string) {}
  speak() { return "..."; }
}
class Dog extends Animal {
  speak() { return this.name + " woofs"; }
}
console.log(new Dog("Rex").speak());
console.log(new Dog("Rex") instanceof Animal);

super and overriding

super.method() calls the parent implementation. Override to specialize; call super when you need to extend rather than replace.

Override + super
class Repo {
  save(entity: string) { return "saved:" + entity; }
}
class AuditedRepo extends Repo {
  save(entity: string) {
    const result = super.save(entity);
    console.log("audit", entity);
    return result;
  }
}
console.log(new AuditedRepo().save("User"));

When not to inherit

If the relationship is has-a, prefer composition. Deep inheritance trees become fragile — Nest codebases favor composing services over deep class hierarchies.

Prefer composition hint
class Logger { log(m: string) { console.log(m); } }
class OrderService {
  constructor(private logger: Logger) {}
  place() { this.logger.log("order placed"); }
}
new OrderService(new Logger()).place();

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

extends models: