Virtual Method Table (vtable) Basics
What you'll learn: How the JVM uses a vtable to quickly find the correct overridden method without searching through entire class hierarchies.
The Efficiency Challenge
When you call an overridden method on an upcast reference, the JVM must determine which version to invoke at runtime—this is dynamic dispatch. But searching through every class in the hierarchy one-by-one would be slow. The JVM solves this with a virtual method table (vtable).
What Is a vtable?
A vtable is like an index or lookup table that each class maintains. Think of it as a phone directory: instead of searching every page to find someone's number, you jump directly to their entry.
When a class is loaded, the JVM builds a vtable containing pointers to the actual method implementations for every instance (non-static, non-final, non-private) method that class can invoke. Each method has a fixed position in the table.
How It Works
When you compile animal.makeSound() where animal is an Animal reference pointing to a Dog object:
- The compiler records the vtable slot number for
makeSound()(e.g., slot 3) - At runtime, the JVM looks at the actual object (
Dog) - It accesses
Dog's vtable at slot 3 - It finds the pointer to
Dog'smakeSound()implementation - It invokes that method directly
This is extremely fast—just two memory lookups—regardless of how deep the inheritance hierarchy is.
Why This Matters
The vtable eliminates the need to search class by class up the hierarchy. Every method call becomes a constant-time operation (O(1)), making polymorphism efficient in production code.
Key Takeaway: The JVM uses a vtable—a lookup table mapping method slots to implementations—to resolve overridden methods in constant time, making dynamic dispatch fast and efficient.