Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Inheritance

One of the most fundamental OOP features is its capability to extend existing classes. This feature is known as inheritance and allows us to create a new class (child class) that inherits all the properties and methods from an existing class (parent class). Child classes can include additional properties and methods that are not available in the parent class.

We are going to use the Person class that we declared in the preceding section as the parent class of a child class named Teacher. We can extend the parent class (Person) by using the reserved keyword extends:

class Teacher extends Person { 
    public teach() { 
        console.log("Welcome to class!"); 
    } 
} 

The Teacher class will inherit all the attributes and methods from its parent class. However, we have also added a new method named teach to the Teacher class.

If we create instances of the Person and Teacher classes, we will be able to see that both instances share the same attributes and methods except for the teach method, which is only available for the instance of the Teacher class:

const person = new Person( 
    "Remo", 
    "Jansen", 
    "remo.jansen@wolksoftware.com" 
); 
 
const teacher = new Teacher( 
    "Remo", 
    "Jansen", 
    "remo.jansen@wolksoftware.com" 
); 
 
person.greet(); // "Hi!" 
teacher.greet(); // "Hi!" 
person.teach(); // Error 
teacher.teach(); // "Welcome to class!"