简体   繁体   中英

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? 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

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

invokes List.add(Object) on an ArrayList. This is like in reflection

It depends on the JVM implementation. 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. Interfaces can't be implemented in O(1) without wasting a lot of memory on sparse tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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