Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JVM Implementation difference between interface and pure abstract class?

Tags:

java

jvm

Me and my friends wondered if there really is a difference inside the JVM between interfaces and pure abstract classes, or if it is just really syntactic sugar.

I don't really see why there would be difference, but it might not be so far-fetched.

like image 901
Manux Avatar asked Jan 18 '23 10:01

Manux


2 Answers

As far as bytecode (.class file) is concerned, they are completely different:

From 4.1 The 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];
}

Clearly class can have a single superclass (abstract or not) and multiple implemented interfaces. It is a limitation of JVM, not a Java (the language) restriction.

like image 128
Tomasz Nurkiewicz Avatar answered Feb 07 '23 04:02

Tomasz Nurkiewicz


There is a performance difference.

Every object has a pointer to its vtable in its object header. The vtable contains pointers to all virtual and abstract methods defined in the hierarchy of the type of the object. They are ordered and have well-known indices which makes it performant to call such a method. Here is how (in pseudo-code)

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

But this scheme falls apart for interfaces because it is not possible to assign static slot numbers in this case (because there can be an huge number of potential interfaces and methods). Because of that interface invocation uses a different technique which is more general and more expensive.

like image 45
usr Avatar answered Feb 07 '23 04:02

usr