简体   繁体   English

Java如何实现接口多态性?

[英]How does Java implement interface polymorphism?

In order to have a pointer to something, you need to know precisely what type it is, and for classes, all the data it contains. 为了拥有指向某物的指针,您需要精确地知道它是什么类型,对于类来说,必须知道它包含的所有数据。 I can see how polymorphism would work for classes: the pointer points to the part of the derived class with the same data as the parent class, and is "unaware" of the additional data below it. 我可以看到多态对于类将如何工作:指针指向派生类中与父类具有相同数据的部分,并且“不知道”其下的其他数据。

How, then does this work for Java interfaces? 那如何在Java接口上工作呢? An interface provides no data, only a guaranteed set of methods. 接口不提供数据,仅提供一组有保证的方法。 There is no unifying data to which a base class pointer could point. 没有任何基类指针可以指向的统一数据。

I'm sorry if this doesn't make sense; 如果这没有道理,我感到抱歉。 I can try to make it clearer. 我可以尝试使其更加清晰。

JVM finds an interface methods in an object by method signature, eg this bytecode JVM通过方法签名(例如,此字节码)在对象中找到接口方法

INVOKEINTERFACE java/util/List.add (Ljava/lang/Object;)Z

invokes List.add(Object) on an ArrayList. 在ArrayList上调用List.add(Object) This is like in reflection 这就像在反思

It depends on the JVM implementation. 它取决于JVM的实现。 Implementation of interfaces is tricky. 接口的实现很棘手。

The simplest solution involves passing two pointers for every parameter that is of interface type. 最简单的解决方案是为接口类型的每个参数传递两个指针。 The first pointer points to the object. 第一个指针指向对象。 The second pointer points to a virtual table that is specific to the derived class and interface combination. 第二个指针指向特定于派生类和接口组合的虚拟表。 With this solution, finding the appropriate second pointer for a particular interface cast involves walking a list linearly. 使用此解决方案,为特定接口强制转换找到合适的第二个指针需要线性遍历一个列表。 It is thus not O(1) , but bounded linearly in the number of implemented interfaces. 因此,它不是O(1) ,而是线性地限制了已实现的接口的数量。 Interfaces can't be implemented in O(1) without wasting a lot of memory on sparse tables. 如果不浪费稀疏表上的大量内存,就无法在O(1)实现接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM