classoopobjectinheritancetypescript1.4

inheritance example from typescript manual


Reading example from typescript manual:

class Animal {
    name:string;
    constructor(theName: string) { this.name = theName; }
    move(meters: number = 0) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(meters = 5) {
        alert("Slithering...");
        super.move(meters);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(meters = 45) {
        alert("Galloping...");
        super.move(meters);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);

The question is about the line var tom: Animal = new Horse("Tommy the Palomino");:


Solution

  • In the example above, Animal is a superclass (also called base class or parent class) of both Horse and Snake. Correspondingly, Horse and Snake are subclasses (derived classes) of Animal.

    When you declare the subclasses:

    class Snake extends Animal
    ...
    class Horse extends Animal
    

    You're telling the compiler that any every Snake and every Horse is in fact, an Animal as well. This makes Animal the broader category in the "world" of the program. Snake and Horse will inherit the properties of Animal, but they can change them (and/or add a few of their own) to be more specialized.