If we want Car to have different drive, simply redefine:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Vehicle { drive(): void{ console.log('chug chug'); } honk(): void { console.log('beep'); } } class Car extends Vehicle { drive(): void { console.log('vroooom'); } } // const vehicle = new Vehicle(); // vehicle.drive(); // vehicle.honk(); const car = new Car(); car.drive(); // vroooom |
Modifiers
public, private, protected – Restrict access
public – can be called any where, any time
private: can be only called by other methods in THIS class.
protected – called by other methods in THIS class, or by other methods in child classes.
by default, it’s public.
If we’re ever over-riding an interface, we cannot change modifier:
If its protected, we can can access in child class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Vehicle { protected honk(): void { console.log('beep'); } } class Car extends Vehicle { private drive(): void { console.log('vroooom'); } startDrivingProcess(): void { this.honk(); // access honk from Vehicle this.drive(); } } const car = new Car(); car.startDrivingProcess(); // beep, vroooom |
shortcut
1 2 3 4 5 6 7 |
class Vehicle { constructor(public color: string) { } ... } |
Also note that if we change it to private, then child classes can’t access it anymore.
In order to be made accessible in child class, we can change it back to public or protected.