Reputation: 3713
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.
Upvotes: 5
Views: 1622
Reputation: 171178
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.
Upvotes: 2
Reputation: 340693
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.
Upvotes: 6
Reputation: 62573
There has to be a difference as abstract classes can hold method implementations where as interfaces can't.
Upvotes: 1