Yajat Dhand’s Post

Polymorphism isn't magic. It's a Lookup Table. I wrote Java for 3 years before I actually understood how the JVM handles Overriding. I relied on the standard university rule: "Method calls are determined by the actual Object type, not the Reference type." While this explains what happens, it doesn't explain how. I imagined the JVM frantically "searching" up the inheritance tree at runtime—scanning the Child class, then the Parent—until it found the method. Architecturally, that would be a disaster. If the JVM had to search the hierarchy (O(N)) for every method call, Java would be too slow for high-performance systems. The JVM avoids this search entirely using vTables (Virtual Method Tables). The Scenario: Imagine we have class B extends A. A has a method print() B overrides show() but inherits print() The Mechanics (Visualized below): Load Time: When Class B is loaded, the JVM builds a hidden array of function pointers. The "Cheat": Since B inherits print(), the JVM simply copies the memory address from A's table into B's table. Runtime: When you run A obj = new B() and call obj.show(), the JVM follows the object in Heap, jumps to the fixed index in the vTable, and runs the code. As the diagram shows: Solid Arrow: The overridden method points to the new B.show() code. Dashed Arrow: The inherited method points back to the existing A.print() code. The Lesson: Efficient systems rarely rely on runtime decisions if they can pre-calculate the answer at load time. (PS: I share more System Design deep dives like this on X. Link in comments 👇) #Java #JVM #SystemDesign #SoftwareArchitecture

  • Java Memory Diagram showing Stack, Heap, and vTable structure for Dynamic Method Dispatch with Class A and Class B.

The fetch/decode/execute cycle is a lookup table; all else follows.

To view or add a comment, sign in

Explore content categories