6

I was just curious if they are treated any differently.

For example if we have:

The interface:

public interface Test {
    public void method();
}

And the abstract class:

public abstract class Test {
    public abstract void method();
}

Will the JVM treat these classes any differently? Which of the two takes up more disk space during storage, which one will use up the most runtime memory which one does more operations(performs better).

This question isn't about when to use interfaces or abstract classes.

nick zoum
  • 7,216
  • 7
  • 36
  • 80
  • Is this question only asking about the memory representation of the class or is it broader question about the differences between abstract class and interface ? – Alexander Petrov Jul 20 '16 at 19:05
  • @AlexanderPetrov i know the differences between these two classes. Obviously if you need to use one of the two listed above you will use the first one. I am just asking if one will need more storage space, will be slightly faster or will use less memory during run time etc. – nick zoum Jul 20 '16 at 19:07
  • @VinceEmigh thanks i forget a couple of things if i don't use an IDE. – nick zoum Jul 20 '16 at 19:11
  • Interesting question man. I've also wondered about this. – Vucko Jul 20 '16 at 19:15
  • 1
    Abstract classes allow your abstract method to have different visibility. It doesn't have to be always public. But hasn't this question already been asked/answered *many* times before? – Hovercraft Full Of Eels Jul 20 '16 at 19:51
  • Yes it has: [Interface vs pure abstract class java](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+interface+vs+pure+abstract+class) – Hovercraft Full Of Eels Jul 20 '16 at 19:51
  • Possible duplicate of [What is the difference between an interface and abstract class?](http://stackoverflow.com/questions/1913098/what-is-the-difference-between-an-interface-and-abstract-class) – Raedwald Jul 25 '16 at 07:02

4 Answers4

7

Yes, they are different.

With an interface, clients could implement it aswell as extend a class:

class ClientType implements YourInterface, SomeOtherInterface { //can still extend other types

}

With a class, clients will be able to extend it, but not extend any other type:

class ClientType extends YourClass { //can no longer extend other types

}

Another difference arises when the interface or abstract class have only a single abstract method declaration, and it has to do with anonymous functions (lambdas).

As @AlexanderPetrov said, an interface with one method can be used as a functional interface, allowing us to create functions "on-the-fly" where ever a functional interface type is specified:

//the interface
interface Runnable {
    void run()
}

//where it's specified
void execute(Runnable runnable) {
    runnable.run();
}

//specifying argument using lambda
execute(() -> /* code here */);

This cannot be done with an abstract class. So you cannot use them interchangably. The difference comes in the limitations of how a client can use it, which is enforced by the semantics of the JVM.

As for differences in resource usage, it's not something to worry about unless it's causing your software problems. The idea of using a memory-managed language is to not worry about such things unless you are having problems. Don't preoptimize, I'm sure the difference is negligable. And even if there is a difference, it should only matter if it may cause a problem for your software.

If your software is having resource problems, profile your application. If it does cause memory issues, you will be able to see it, as well as how much resources each one consumes. Until then, you shouldn't worry about it. You should prefer the feature that makes your code easier to manage, as opposed to which consumes the least amount of resources.

Vince
  • 14,470
  • 7
  • 39
  • 84
  • 1
    My thoughts exactly, but I don't think this necessarily answer the question he asked. He asked about how JVM sees these two. – Vucko Jul 20 '16 at 19:14
  • @Vucko He's actually asking "***Will the JVM treat these classes any differently?***" rather than "***How does the VM treat these under the hood?***". He could have no experience with bytecode, and simply wants to know if they are interchangable. I answered "they are different", and mentioned the differences in how they work (requiring different semantics under-the-hood). He should clarify in his answer if he wants to know *how* the VM handles it, because the question currently doesn't express that. – Vince Jul 20 '16 at 19:19
  • @Vucko It is a difference that i did not know about. I thought in java you could only implement one class. – nick zoum Jul 20 '16 at 19:19
  • I agree with you Vince, this is a useful answer, don't get me wrong. Nick, yes, in Java you can extend a maximum of one class but you can implement unlimited number of interfaces. Therefore the difference in this sense exists, of course. – Vucko Jul 20 '16 at 19:20
  • @VinceEmigh So is that only difference? And would this be any different for C++ or C#, since they can have multiple inheritance? Wouldn't they be exactly the same? – nick zoum Jul 20 '16 at 19:31
  • Sory for Hijacking the thread , but in my opinion this answer is not relevant to the question. As long as the question about how the JVM is threating the classes stands. – Alexander Petrov Jul 20 '16 at 19:37
  • @AlexanderPetrov No worries, you are not hi-jacking. You are simply expressing your opinion. Mind repeating the question to me? Just in-case I misunderstood what was asked in the post – Vince Jul 20 '16 at 20:08
  • Of course it is my understanding, but the way I see the question it is not about the "functional" differences of interface and abstract class, but how the JVM is translating them and treating them internally. Do you gain smaller memory footprint if you use interface over abstract class. Do you gain performance if you use abstract class. This is how I understand the question. I will quote the last two sentences of his question "Will the JVM treat these classes any differently? Which of the two takes up more disk space during storage, which one will use up the most memory." – Alexander Petrov Jul 20 '16 at 20:14
  • @AlexanderPetrov I updated my post. The first question was already answered, I edited in an answer for his second question (although it should be asked in a different post to abide by SO standards) – Vince Jul 20 '16 at 20:20
  • I was just focused on the "This question isn't about when to use interfaces or abstract classes." comment in bold :) – Alexander Petrov Jul 20 '16 at 20:28
  • @AlexanderPetrov Yes, I noticed that. And this question does not describe the preferred use cases of each. It describes how they are not interchangeable by describing the differences, which are enforced by the VM's semantics – Vince Jul 20 '16 at 20:35
5

JVM internals and memory representation It will be almost the same for the JVM. My statement is based on Chapter 4 - Class file Format. As seen from the attached documentation the JVM is making difference between a class and interface, by the access_flags. If you have a Simple interface with just one method and a simple abstract class with just one method. Most of the fields in this format will be the same (empty) and the main difference will be the access_flags.

Default constructor generation abstract class As @Holger pointed out, another small difference between the Interface and Abstract class is that ordinary classes require a constructor. The Java compiler will generate a default constructor for the Abstract class which will be invoked for each of its subclasses. In that sense the abstract class definition will be slightly bigger compared to the interface.

https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html

ClassFile {
    u4             magic;
    u2             minor_version;
    u2             major_version;
    u2             constant_pool_count;
    cp_info        constant_pool[constant_pool_count-1];
    u2             access_flags;
    u2             this_class;
    u2             super_class;
    u2             interfaces_count;
    u2             interfaces[interfaces_count];
    u2             fields_count;
    field_info     fields[fields_count];
    u2             methods_count;
    method_info    methods[methods_count];
    u2             attributes_count;
    attribute_info attributes[attributes_count];
}

Besides the multiple inheritance of interfaces, another difference is that in Java8 abstract class with only one method is not a Functional interface.

 @FunctionalInterface
 public interface SimpleFuncInterface {
      public void doWork();
 }

 execute(SimpleFuncInterface function) {
      function.doWork();
 }

 execute(()->System.out.printline("Did work"));

Same can not be achieved with abstract class.

Interfaces - lack of "Openness to extension". Up to Java 8 Interfaces have been criticized for their lack of extensibility. If you change the interface contract you need to refactor all clients of an interface.

One example that comes to mind is Java MapReduce API for Hadoop, which was changed in 0.20.0 release to favour abstract classes over interfaces, since they are easier to evolve. Which means, a new method can be added to abstract class (with default implementation), with out breaking old implementations of the class.

With the introduction of Java 8 Interface Default method this lack of extensibility has been addressed.

public interface MyInterface {
 int method1();
 // default method, providing default implementation
 default String displayGreeting(){
  return "Hello from MyInterface";
 }
}

With Java 8 new methods can be added both to interfaces and abstract classes without breaking the contract will the client classes. http://netjs.blogspot.bg/2015/05/interface-default-methods-in-java-8.html

Alexander Petrov
  • 9,204
  • 31
  • 70
  • I'm not sure what "*lack of interface extensibility*" in previous Java versions (and the Java 8 improvement) has to do with the question. You were pretty stern about my answer straying away from the point (which it didn't, you just made it clear that your interpretation of the question was most important), yet you're going to include irrelevant info that, although is related to interface, has *nothing* to do with the question at hand. You, sir, have blown my mind with your blantant hypocrisy. – Vince Aug 13 '16 at 03:42
1

They are different in implementation

  • you can only extend only one abstract class
  • On the other hand you can implement multiple interfaces at the same time
  • You need to implement all method present in an interface
  • for abstract it may provide some default implementation so you are independent whether you want to implement it again or just used the default implementation
0

If you talking about performance, then sometime ago there was an opinion that interfaces are slower than abstract classes. But now JIT makes no difference between them.

Please, see this answer for more details.

Community
  • 1
  • 1
Michael Spitsin
  • 2,539
  • 2
  • 19
  • 29