Virtual Method Table (VMT) & Dynamic Method Dispatch
1Concept
In Java, all non-final, non-private instance methods are virtual by default. The JVM resolves overridden method calls dynamically at runtime using a Virtual Method Table (vtable). Each class has a vtable pointing to the actual executable function pointers in memory.
2Architecture Diagram
[ PaymentService Ref ] ---> Runtime points to [ CryptoPaymentService Object ]
|
v [ CryptoPaymentService vtable ]
processPayment() -> points to Crypto logic3Code Example
Core Java
public class DynamicDispatchDemo {
abstract static class Notification {
abstract void send(String msg);
}
static class EmailNotification extends Notification {
void send(String msg) { System.out.println("Email Dispatch: " + msg); }
}
static class SmsNotification extends Notification {
void send(String msg) { System.out.println("SMS Gateway Dispatch: " + msg); }
}
public static void main(String[] args) {
Notification[] channels = {
new EmailNotification(),
new SmsNotification()
};
for (Notification channel : channels) {
channel.send("Deployment Completed Successfully"); // Dynamic vtable lookup
}
}
}4Expected Output
Email Dispatch: Deployment Completed Successfully SMS Gateway Dispatch: Deployment Completed Successfully
5Key Takeaways
- ✓Dynamic dispatch executes via bytecode `invokevirtual` opcode.
- ✓HotSpot JIT devirtualizes monomorphic call sites to inline methods directly.
- ✓Variables are bound by reference type at compile time, but executed by object type at runtime.