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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With