How is method overriding implemented in Java? In C++ we have the concept of vtable.. how is this implemented internally in Java?
To answer the question, which is specifically how overriding is implemented in the virtual machine, there's a write up available in Programming for the Java Virtual Machine (Google Books link).
The VM will look for an appropriate method definition in the referenced class, and then work its way up through the inheritance stack. Obviously at some stage various optimisations will apply.
See here for a description of the relevant bytecode instruction invokevirtual
:
invokevirtual looks at the descriptor given in , and determines how many arguments the method takes (this may be zero). It pops these arguments off the operand stack. Next it pops objectref off the stack. objectref is a reference to the object whose method is being called. invokevirtual retrieves the Java class for objectref, and searches the list of methods defined by that class and then its superclasses, looking for a method called methodname, whose descriptor is descriptor.
As gustafc has highlighted below, various optimisations can apply, and no doubt the JIT will introduce further.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With