Reputation: 660
In Java all public non static methods are virtual. This means that which method to call is decided on run time(dynamic binding). In C++ virtual functions (dynamic binding) is implemented by using vpointer and vtable. I want to know that how this is implemented by Java. Does Java also use vpointer and vtable like C++ or some other technique to know which method to call on run time?
Upvotes: 5
Views: 4730
Reputation: 46862
vtables, as described at https://wiki.openjdk.org/display/HotSpot/VirtualCalls
[edit Tomasz makes a good point in the question comments - this is for Oracle's hotspot]
Upvotes: 5
Reputation: 11805
Not all non static methods are bound at runtime. In may cases, it can be determined at compile time which version of a method needs to be called. In particular, when the compiler can with 100% certainty determine which method needs to be called. One such easy situation:
public class Foo {
public final void foo() { ... }
public void bar() { ... }
public void bar(String s) { ... }
}
Foo foo = new Foo();
// All three of these could would be bound at compile time.
foo.foo();
foo.bar();
foo.bar("baz");
There are also cases based on overloading where a compile time binding can be determined. I'm not 100% sure what all the different cases are, but there are a few.
Here's a good article on the subject:
http://www.dzone.com/links/r/difference_between_static_and_dynamic_binding_in.html
Upvotes: 0
Reputation: 47699
Basically, it's implemented (conceptually) using a virtual function table, and indexes into that. But there are a number of twists, notably "invokespecial" calls and interface calls, where additional/different processing is required.
In practice, a lot of the data is cached, to improve call efficiency.
Upvotes: 0
Reputation: 200138
Since this is the world of the Java Virtual Machine, the story is not that simple. The best you can do is learn about all the dozens of tricks employed for all the various special cases. This wouldn't be a bad starting point: Inline caching.
Upvotes: 0