Start learning free

LESSON 650 OF 675 · OBJECT-ORIENTED PROGRAMMING

OOP Capstone — Animal Hierarchy in TypeScript

Lesson

TL ; DR:

Put it all together: a parent class with a placeholder method, three subclasses that override it, and a polymorphic loop that dispatches by runtime type. This is the shape of nearly every real OOP design.


class Animal {
    name: string;
    constructor(name: string) { this.name = name; }
    sound(): string { throw new Error("Not implemented"); }
    speak(): void {            // shared by all
        console.log(this.name + ": " + this.sound());
    }
}
// Dog, Cat, Bird each override sound
// const zoo: Animal[] = [new Dog("Rex"), ...];
// for (const a of zoo) a.speak();


Full lesson:

This problem stitches together everything you've learned in this chapter:

  1. Inheritance — three concrete classes share a common parent.
  2. Constructors — the subclasses declare none, so each one uses the parent's constructor, which stores the name.
  3. Overriding — the parent's sound() is only a placeholder that throws an error; each child overrides it with its own version.
  4. Shared behavior — the parent has a concrete speak() that calls sound(); every subclass inherits it for free.
  5. Polymorphism — a collection typed as Animal holds a Dog, a Cat, and a Bird; speak() dispatches to the right sound() at runtime.

The shape of this code is the shape of nearly every real OOP design you'll see — a small contract at the top (the parent class), concrete variants below, and the rest of the program written against the parent type. New variants get added without touching the consumer code.


Your task

The Animal class is already defined, with a concrete speak() that calls sound(). Add three subclasses — Dog (returns "Woof"), Cat (returns "Meow"), and Bird (returns "Tweet"). Then build an Animal[] holding one of each (Rex, Whiskers, Tweety in that order) and loop through it with for...of, calling speak().

Expected output:

Rex: Woof
Whiskers: Meow
Tweety: Tweet
STEP 1 OF 5
    Ctrl + Enter to check