Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method overriding in Java

How is method overriding implemented in Java? In C++ we have the concept of vtable.. how is this implemented internally in Java?

like image 783
ria Avatar asked Oct 09 '09 11:10

ria


1 Answers

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.

like image 117
Brian Agnew Avatar answered Sep 28 '22 17:09

Brian Agnew