Method overriding

Sometimes, we will need a child class to provide a specific implementation of a method that is already provided by its parent class. We can use the reserved keyword super for this purpose.

We are going to use, once more, the Person and Teacher classes declared during the Inheritance section in this chapter.

Imagine that we want to add a new attribute to list the teacher's subjects, and we want to be able to initialize this attribute through the teacher constructor. We are going to use the super keyword to explicitly reference the parent class constructor inside the child class constructor:

class Person { 
    public constructor( 
        public name: string, 
        public surname: string, 
        public email: string 
    ) {} 
    public greet() { 
        console.log("Hi!"); 
    } 
} 
 
class Teacher extends Person { 
    public constructor( 
        name: string, 
        surname: string, 
        email: string, 
        public subjects: string[] 
    ) { 
        super(name, surname, email); 
        this.subjects = subjects; 
    } 
    public greet() { 
        super.greet(); 
        console.log("I teach " + this.subjects.join(" & ")); 
    } 
    public teach() { 
        console.log("Welcome to class!"); 
    } 
} 

We have also used the super keyword to extend an existing method, such as greet. This OOP language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by its parent classes is known as method overriding.

At this point, we can create an instance of the Person and Teacher classes to observe their differences:

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