Subclass takes up more memory than superclass

An object initiated by class B, which inherits from class A, takes up more memory on the heap than an object initiated by class A. Following are the two scenarios I have considered:

Scenario 1:

class A {
  String name;
}

class B extends A {

}

      

Scenario 2:

class A {
  String name;
}

class B extends A {
  int age;
}

      

+3


source to share


1 answer


Looking at your examples:

  • Scenario # 1: there should be no difference in size between instance A

    and instanceB

  • Scenario # 2: An instance B

    can take up more space than an instance A

    , but it depends on the word alignment and whether you are using a 32 or 64-bit JVM and / or have "compressed oops". In short, the answer is JVM specific.



In a generic subclass by itself, it does not entail additional memory per instance, but additional fields may be executed, depending on how the JVM exposes the instance fields on the node heap.

But I agree with the comments. The Java programmer does not need to worry about this. The size difference is likely to be so small as to be irrelevant ... unless you need to create millions of these objects. And even then, there are probably more important things to worry about.

+5


source







All Articles