4

Where do the method reside? For example,

class Foo {
  public void foo_test(){}
}

Foo f1 = new Foo();
f1.foo_test();

(new Foo() {
  public void singleton_test(){
    foo_test();
  }
}).singleton_test();

Do the methods reside in the class or the instances?

Does JVM do a method lookup (like C++ vtable)? How do the above 2 invocations of methods take place?

I was looking at this page:

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html

But it only briefly explains the lookup procedure, not the place or any details.


This question is specifically related Oracle JVM.

SwiftMango
  • 15,092
  • 13
  • 71
  • 136

1 Answers1

1

All methods in Java are virtual except the ones marked as static. Your second example simply creates an anonymous inner class, which behaves almost exactly like a named class. (It behaves exactly the same from this perspective.)

The exact mechanism for method lookup isn't specified, it's up to the VM implementation. This allows room for smart optimisation too, for example if a method isn't overriding another and is marked as final, it can decide there's no need for an extra indirection.

biziclop
  • 48,926
  • 12
  • 77
  • 104
  • So it does virtual method lookup like C++? Does it have a vtable or symbolic table? How does Oracle JVM implement this? – SwiftMango Sep 29 '14 at 18:00
  • @texasbruce There are a multitude of strategies, so it's difficult to say. The basic method will be something like a vtable but code is optimised runtime too by the JIT compiler, so a method may even end up completely inlined into the calling code. But from a high-level point of view it should always behave as if the methods were virtual. – biziclop Sep 29 '14 at 18:20
  • Here's some more reading on the subject: http://stackoverflow.com/questions/1504633/what-is-the-point-of-invokeinterface – biziclop Sep 29 '14 at 18:33