Java中的方法覆盖 [英] method overriding in Java

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

问题描述

如何在Java中实现方法重写?在C ++中我们有vtable的概念..这是如何在Java内部实现的?

How is method overriding implemented in Java? In C++ we have the concept of vtable.. how is this implemented internally in Java?

推荐答案

回答这个问题,这是特别是在虚拟机中如何实现覆盖,可以在 Java虚拟机编程(Google图书链接)。

To answer the question, which is specifically how overriding is implemented in the virtual machine, there's a write up available in Programming for the Java Virtual Machine (Google Books link).

VM将在引用的类中查找适当的方法定义,然后通过继承堆栈向上工作。显然在某些阶段会适用各种优化措施。

The VM will look for an appropriate method definition in the referenced class, and then work its way up through the inheritance stack. Obviously at some stage various optimisations will apply.

参见这里描述了相关的字节码指令 invokevirtual

See here for a description of the relevant bytecode instruction invokevirtual:

invokevirtual查看给定的描述符
,并确定
该方法需要多少参数
(这可能为零)。它从操作数堆栈中弹出这些
参数。接下来
它会将objectref从堆栈中弹出。
objectref是对正在调用其方法的对象
的引用。
invokevirtual为objectref检索Java类
,并搜索该类定义的方法列表

然后查找其超类,查找名为methodname的
方法,其
描述符是描述符。

invokevirtual looks at the descriptor given in , and determines how many arguments the method takes (this may be zero). It pops these arguments off the operand stack. Next it pops objectref off the stack. objectref is a reference to the object whose method is being called. invokevirtual retrieves the Java class for objectref, and searches the list of methods defined by that class and then its superclasses, looking for a method called methodname, whose descriptor is descriptor.

正如gustafc在下面强调的那样,可以应用各种优化,毫无疑问,JIT将会引入进一步。

As gustafc has highlighted below, various optimisations can apply, and no doubt the JIT will introduce further.

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

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