BeCuriouzLearn something new every day
extends, super, and abstract: Building on What Came Before
💡 Use extends/super to build on a parent class, and abstract to define a base that can't be instantiated but forces subclasses to fill in required methods.
In the last cards you built single classes with fields and methods. Inheritance lets one class reuse and extend another. A subclass uses extends to inherit everything from a base class, then adds or overrides behavior:
class Animal {
constructor(public name: string) {}
speak(): string { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
speak(): string { return `${this.name} barks`; } // override
}When a subclass has its own constructor, it MUST call super(...) before touching this — super runs the parent's constructor to initialize inherited fields. You can also call super.method() to reuse the parent's version instead of fully replacing it:
class Puppy extends Dog {
constructor(name: string, public age: number) {
super(name); // required: initialize Animal's `name`
}
speak(): string { return `${super.speak()} (age ${this.age})`; }
}Sometimes a base class only exists to be extended — it makes no sense on its own. Mark it abstract: it can't be instantiated with new, and it can declare abstract methods with no body that every subclass is forced to implement. This is a compile-time contract: new Shape() becomes a type error, and forgetting area() in a subclass won't compile.
abstract class Shape {
abstract area(): number; // no body — subclasses must supply one
describe(): string { return `Area is ${this.area()}`; }
}
class Circle extends Shape {
constructor(public r: number) { super(); }
area(): number { return Math.PI * this.r ** 2; }
}