开发者

Java - Virtual Methods

How does virtual functions work behind the scenes in Inheritance ? Does the compiler treat virtual functions specially ?开发者_Go百科


All methods in java are virtual by default. That means that any method can be overridden when used in inheritance, unless that method is declared as final or static.


'Virtual' is a C++ term. There are no virtual methods in Java. There are ordinary methods, which are runtime-polymorphic, and static or final methods, which aren't.


Yes, virtual methods are treated differently by the compiler and the runtime. The JVM specifically utilizes a virtual method table for virtual method dispatch:

An object's dispatch table will contain the addresses of the object's dynamically bound methods. Method calls are performed by fetching the method's address from the object's dispatch table. The dispatch table is the same for all objects belonging to the same class, and is therefore typically shared between them. Objects belonging to type-compatible classes (for example siblings in an inheritance hierarchy) will have dispatch tables with the same layout: the address of a given method will appear at the same offset for all type-compatible classes. Thus, fetching the method's address from a given dispatch table offset will get the method corresponding to the object's actual class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜