2

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.

2
  • Because the interface guarantees the contract (or set of methods). Commented Apr 7, 2015 at 4:33
  • @ElliottFrisch I don't understand; you can't point to a method, can you? Are you saying interfaces use a function pointer field for every one of their methods? Commented Apr 7, 2015 at 4:38

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

I don't get why an answer like this would get upvotes. It explains nothing about how the JVM actually implements interface calls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.