tags:

views:

234

answers:

3

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

A: 

As long as the function (method) you wish to override is not marked as final you just simply override the method by extending the class which holds that method and then provide a method with same signature but different body.

seb
Again, does this address the question, though, which is asking about the internal implementation (e.g. via vtables or similar) ?
Brian Agnew
+9  A: 

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.

Brian Agnew
It's relevant to remember that `invokevirtual` and `invokeinterface` calls can actually result in inlined code - if the callee only is implemented by one loaded class, there's no need to search through every class's methods. If there's two classes implementing the methods, the call is JITted into an `if` / `else` checking the type of the object, which also is faster than making a method lookup.
gustafc
A: 

Maybe this comparison of C++ Vtables and Java method invocation tables is of interest.

Reuben Peeris