Java - Virtual Methods

前端 未结 3 836
暗喜
暗喜 2020-12-08 16:23

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

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 16:56

    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.

提交回复
热议问题