Interview frequency: …
Short answer
Polymorphism is the ability of different objects to respond to the same message in different ways. Static dispatch is resolved at compile time (such as method overloading), while dynamic dispatch is resolved at runtime through virtual function tables (vtables).
Explanation
In statically typed languages such as C++, C#, and Java, dynamic dispatch uses a Virtual Method Table (vtable). Each object has a pointer to its class's vtable. When a virtual method is called, its address is looked up at runtime. This adds a small processing cost but provides substantial architectural flexibility.
Code example
interface Shape {
draw(): void;
}
class Circle implements Shape { draw() { console.log('Circle'); } }
class Square implements Shape { draw() { console.log('Square'); } }
function render(shapes: Shape[]) {
for (const s of shapes) s.draw(); // Dynamic Dispatch Runtime
}Common mistakes
- Believing that overloading and overriding work the same way in memory and at runtime.