Java - 虚拟方法 [英] Java - Virtual Methods

查看:72
本文介绍了Java - 虚拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虚拟功能如何在继承中的幕后工作?
编译器是否特别处理虚函数?

How does virtual functions work behind the scenes in Inheritance ? Does the compiler treat virtual functions specially ?

推荐答案

是的,编译器和运行时对虚拟方法的处理方式不同。 JVM专门使​​用虚拟方法表进行虚拟方法调度:

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


对象的调度表将
包含对象的
动态绑定方法的地址。方法
调用是通过从对象的
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.

这篇关于Java - 虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆