Polymorphism Examples in Object Oriented Programming (OOP) Differing From Static, Compile-Time Polymorphism (Operator Overloading) as it Can Run Dynamically. Showcasing Generic, Subtype & Parametric Polymorphism
Polymorphism reduces duplication and makes APIs flexible. For example, a "start" action can mean igniting an engine for a car, playing a disc for a DVD player, or booting a computer — same action, different implementations.
A subclass provides its own implementation of a method defined in its superclass.
class Device {
start(): void {
console.log("Starting device");
}
}
class Car extends Device {
start(): void {
console.log("Igniting engine");
}
}
class DVDPlayer extends Device {
start(): void {
console.log("Beginning playback");
}
}
const devices: Device[] = [new Car(), new DVDPlayer()];
devices.forEach(d => d.start());
// Output:
// Igniting engine
// Beginning playback
A function or class works with multiple types specified at use time.
function identity<T>(value: T): T {
return value;
}
const s = identity<string>("hello");
const n = identity<number>(42);