Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between abstract class and interface in terms of their storage in JVM [duplicate]

What is the difference between abstract class and interface in terms of their storage in JVM. To be more precise where does JVM store interfaces into its memory?

like image 992
Sharda Prasad Jaiswal Avatar asked Jun 15 '15 10:06

Sharda Prasad Jaiswal


2 Answers

Warning: As was mentioned by @assylias, this mechanics are specific for Oracle HotSpot JVM.

Before Java8

All meta information is stored in PermGen, for both abstract classes and interfaces. Meta information includes only class specific information (what fields it has, what is parent, etc).

Interface can have only public static final fields, so this field meta information is stored in PermGen.

Abstract class can have both static and non-static fields. However, there is no difference in terms of meta information, so it is all stored in PermGen too. On the other hand, real object instances are stored in Heap for both static and non-static fields.

See the example

public class MyClass {
   public static final Calendar calendar = Calendar.getInstance();
   private Date myDate = new Date();
}

Field information about calendar and myDate is stored in PermGen and real object instances are stored in Heap.

In Java8 PermGen was moved inside the Heap space, in so-called Metaspace, so you will not see java.lang.OutOfMemoryError: PermGen space anymore. However, conceptual separation between meta information and object allocation memory is still present.

Also review @AlexTaylor specification quotation.

like image 74
AdamSkywalker Avatar answered Oct 18 '22 11:10

AdamSkywalker


The method area (logically part of the heap) stores a lot of information about classes and interfaces in the JVM:

...stores per-class structures such as the run-time constant pool, field and method data, and the code for methods and constructors, including the special methods (§2.9) used in class and instance initialization and interface initialization.

However:

This specification does not mandate the location of the method area or the policies used to manage compiled code.

Which means a particular JVM is free to store them wherever it pleases.

like image 36
Alex Taylor Avatar answered Oct 18 '22 10:10

Alex Taylor