Java - 虚拟方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2486160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Virtual Methods
提问by sgokhales
How does virtual functions work behind the scenes in Inheritance ? Does the compiler treat virtual functions specially ?
虚函数在继承中如何在幕后工作?编译器是否特别对待虚函数?
采纳答案by Andrew Hare
Yes, virtual methods are treated differently by the compiler and the runtime. The JVM specifically utilizes a virtual method tablefor virtual method dispatch:
是的,编译器和运行时对虚拟方法的处理方式不同。JVM 专门利用一个虚方法表进行虚方法调度:
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.
对象的调度表将包含对象的动态绑定方法的地址。方法调用是通过从对象的调度表中获取方法的地址来执行的。分派表对于属于同一类的所有对象都是相同的,因此通常在它们之间共享。属于类型兼容类的对象(例如继承层次结构中的兄弟)将具有相同布局的调度表:给定方法的地址将出现在所有类型兼容类的相同偏移量处。因此,从给定的调度表偏移量中获取方法的地址将获得与对象的实际类对应的方法。
回答by Kevin Crowell
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.
默认情况下,java 中的所有方法都是虚拟的。这意味着在继承中使用任何方法都可以被覆盖,除非该方法被声明为 final 或 static。
回答by user207421
'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.
“虚拟”是一个 C++ 术语。Java 中没有虚方法。有普通方法,它们是运行时多态的,还有静态或最终方法,它们不是。