您的位置:首页 > 编程语言 > Java开发

JAVA中虚方法的调用(Virtual Method Invocation)

2014-04-02 22:30 429 查看
在多态的情况下,声明为父类类型的引用变量只能调用父类中的方法,但如果此变量实际引用的是子类对象,而子类对象中覆盖了父类的方法,这时父类对象调用的是子类中的方法,这种机制就成为虚方法调用。

所以,同样的两个引用变量调用相同的方法结果可能不同。

In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are
not inherited, are non-virtual.

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: