JVM Difference in implementation between an interface and a pure abstract class?

My friends and I wondered if there was a difference between the JVM between interfaces and pure abstract classes, or if it was really syntactic sugar.

I really don’t understand why there will be a difference, but it may not be so far-fetched.

+4
source share
3 answers

As for the bytecode ( .class file), they are completely different:

From 4.1 ClassFile Structure :

 ClassFile { //... u2 constant_pool_count; cp_info constant_pool[constant_pool_count-1]; //... u2 super_class; u2 interfaces_count; u2 interfaces[interfaces_count]; } 

It is clear that a class can have one superclass ( abstract or not) and several implemented interfaces. This is a limitation of the JVM, not a limitation of Java (language).

+5
source

There is a difference in performance.

Each object has a pointer to its own vtable in the object header. Vtable contains pointers to all virtual and abstract methods defined in the object type hierarchy. They are ordered and have well-known indexes that make it efficient to call such a method. Here's how (in pseudo code)

 obj.vtable[0].call(); //this calls the method in the first slot (which might well be toString) 

But this scheme is falling apart for interfaces, because in this case it is impossible to assign numbers of static slots (since there can be a huge number of potential interfaces and methods). Because of this invocation of the interface, a different method is used, which is more general and more expensive.

+2
source

There should be a difference, since abstract classes may contain implementations of methods where interfaces cannot be.

+1
source

Source: https://habr.com/ru/post/1397666/


All Articles