gpt4 book ai didi

java - JVM如何解析java中的重写和覆盖方法

转载 作者:行者123 更新时间:2023-12-01 09:31:04 25 4
gpt4 key购买 nike

根据我对 C++ 多态性的了解(如果我错了,请纠正我)

对于 C++ 中的运行时多态性,编译器维护两件事,首先是每个对象的 vptr 和每个类的 vtable。每当我们调用一个重写的方法时,编译器首先获取引用对象的vptr,然后转到相应类的vtable,然后获取相应方法的地址并执行。

现在我的问题是,

JVM如何执行这个任务?

它还维护一个 vtable 吗?

一个被重写和重写的方法是如何存储在方法区的?

当我们使用引用子类对象的父类(super class)引用从子类调用重写方法时,幕后实际发生了什么?

最佳答案

这在 invokevirtual 的规范中进行了描述

Let C be the class of objectref. The actual method to be invoked is selected by the following lookup procedure:

  • If C contains a declaration for an instance method m that overrides (§5.4.5) the resolved method, then m is the method to be invoked, and the lookup procedure terminates.

  • Otherwise, if C has a superclass, this same lookup procedure is performed recursively using the direct superclass of C; the method to be invoked is the result of the recursive invocation of this lookup procedure.

  • Otherwise, an AbstractMethodError is raised.

关于java - JVM如何解析java中的重写和覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39390668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com