Inheritance and Polymorphism
Method Overriding
A child class can override a parent method to provide specialized behavior.
Method Overriding
override.ts
class Notification {
message: string;
constructor(message: string) {
this.message = message;
}
format(): string {
return this.message;
}
}
class UrgentNotification extends Notification {
format(): string {
return `URGENT: ${this.message.toUpperCase()}`;
}
}
const rawMessage: string = ;
const notice: Notification = new UrgentNotification(rawMessage);
const formatted: string = notice.format();
console.log(formatted);
class Notification {
message: string;
constructor(message: string) {
this.message = message;
}
format(): string {
return this.message;
}
}
class UrgentNotification extends Notification {
format(): string {
return `URGENT: ${this.message.toUpperCase()}`;
}
}
const rawMessage: string = ;
const notice: Notification = new UrgentNotification(rawMessage);
const formatted: string = notice.format();
console.log(formatted);
class Notification {
message: string;
constructor(message: string) {
this.message = message;
}
format(): string {
return this.message;
}
}
class UrgentNotification extends Notification {
format(): string {
return `URGENT: ${this.message.toUpperCase()}`;
}
}
const rawMessage: string = ;
const notice: Notification = new UrgentNotification(rawMessage);
const formatted: string = notice.format();
console.log(formatted);
override
An overriding method has the same name as the parent method and runs for the child instance.