Well, no one can answer this because it depends on JVM implementation and it varies from JVM to JVM.
And from the above statements, we can conclude that an object reference indirectly holds a reference/pointer to a table which holds all the method references of that object.
Java has borrowed this concept from C++ and this table is known by various names which such as virtual method table ( VMT ), virtual function table ( vftable ), virtual table ( vtable ), dispatch table.
We can not sure of how vtable is implemented in Java because it is JVM dependent.
But we can expect that it will be following the same strategy as C++ where vtable is an array like structure which holds method names and their references on array indices.
And whenever JVM try to execute a virtual method it always asks the vtable for it address.
There is only one vtable per class means it is unique and same for all objects of a class similar to Class object.
I have discussed more on Class object in my articles Why an outer Java class can’t be static and Why Java is Purely Object-Oriented Language Or Why Not.
So there is only one vtable for Object class which contains all 11 methods (if we don't count registerNatives) and references to their respective method bodies.
When JVM loads the Mammal class into memory it creates a Class object for it and creates a vtable which contains all the methods from the vtable of Object class with the same references (Because Mammal is not overriding any method from Object) and adds a new entry for speak method.
Now here comes the turn of Human class and now JVM will copy all entries from the vtable of Mammal class to the vtable of Human and adds a new entry for the overloaded version of speak(String).
JVM knows that Human class has overridden two methods one is toString() from Object and second is speck() from Mammal .
Now instead of creating new entries for these methods with updated references.
JVM will modify the references to the already present methods on the same index where they were present earlier and will keep the same method names.
The invokevirtual causes the JVM to treat the value at method reference #4 , not as an address but as the name of a method to look up in the vtable for the current object.
I hope now it would have become a little bit clear that how the JVM mixes constant pool entries and vtable to conclude which method it is going to call.
You can find complete code on this Github Repository and please feel free to provide your valuable feedback.
Originally published at www.
.. More details