Java memory usage in inheritance

What memory usage in Java looks like when extending a base class.

Does the child class provide an instance of the base class (with its own utility and all) or does it have only its own utility data of 16 bytes?

class Foo { int x; } class Bar extends Foo { int y; } 

So, more precisely, what is the memory usage of the Bar instance?

This is Foo (including overhead) + Bar(including overhead)

or just Foo (excluding overhead + Bar(including overhead)

+8
java inheritance memory subclass
source share
2 answers

No double overhead.

Java will take the class, superclasses, calculate the space needed for all fields, and allocate the space needed for one instance.

Create only a memory point, there is no concept of a superclass at all, there is an instance of Foo that needs memory for only one int, and instances of Bar that need memory for two ints, of which one is there, because Bar appears to be expanding Foo.

This way, overhead (or bookkeeping or whatever you want to call) happens only once.

However, when developing in java it is usually better not to care about the memory material too much unless you have very specific (and I mean very very specific) use cases in which the overhead of the book causes serious problems. In this case, an 8-byte addition should also be considered.

There are usually many other ways to improve the memory size of your application or its overall performance, rather than worry about the memory overhead of each individual instance.

+8
source share

There is only one class header for each object, so it has only the last.

By the way, you can easily check this using https://sourceforge.net/projects/sizeof/ or https://code.google.com/p/memory-measurer/

+2
source share

All Articles