开发者

Java Interfaces

What is meant by virtual table resolution strategy used by JVM ? Can somebody expla开发者_StackOverflow社区in in detail ?


Basically any method that is not declared final can be overriden in any inheriting class. A virtual table resolution strategy is how Java dynamically dispatches method invocations to the method definition of the runtime type of the object. For example, if you have an object s that is declared to be of type Shape but was instantiated as new Circle() (i.e. Shape s = new Circle()) and then you invoke s.draw()... if Circle overrides draw, you want the Circle's version of the draw method to be invoked and not the Shape's version of that method. This information can only be figured out at runtime (if you are passed a Shape object, it could be passed in from a JAR that the compiler never sees, so the compiler has no way of figuring out what specific subclass of Shape was instantiated), and so it is up to the VM to dispatch the method invocation to the correct method definition (in this case, the version of draw provided by Circle).

// Shape.java
public class Shape
{
     public void draw(){
        System.out.println("I'm a Shape");
     }
}


// Circle.java
public class Circle extends Shape
{
     public void draw(){ 
          System.out.println("I'm a Circle");
     }
}

// Elsewhere
Shape s = new Circle();
s.draw(); // should print "I'm a Circle"

With most implementations of a virtual table, each class has a table where each entry is a member function and its corresponding address. So, the virtual table for Circle and Shape would both have an entry in the table for "draw", but the virtual table for Circle and Shape each have the entry for draw point to their respective definitions of that function. Then, each instance of the class points to the virtual table of its given class. So, when you do new Circle(), it contains an entry pointing to the virtual table of Circle. When a method that is not declared final is invoked, the appropriate method implementations is invoked by looking up the appropriate offset into the object's virtual table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜