Memory allocation for a class in java?

class B inherits class A. Now that we are creating an object of type B, what is the memory allocated for B? Does it include A and B or any other procedure for allocating memory?

+2
java object inheritance memory
Oct 06 2018-11-11T00:
source share
3 answers

When you create object B, say by calling the default constructor

B myObject = new B(); 

The JVM then allocates the object more or less:

  • There is enough memory for each field explicitly declared in B (usually about 4-8 bytes per field, but it varies greatly between types and host system).
  • Enough memory for every possible field inherited by A and his ancestors
  • Enough memory to contain a link to the send vector (which should also be about 4-8 bytes)

The send vector is used by the compiler to store the address of each method that can be called for a given object, and depends on the class of the object, and not on the instance of the object itself (each object B has the same interface in the end!)

Therefore, you do not need to select A because there is no separate object A. You do not create 2 separate objects. When you create B, you create a β€œspecialized” version of A .. that can be thought of as A with something more. Therefore, you need to select only B (but keep in mind that B also has everything that its ancestors have)

+1
06 Oct 2018-11-11T00:
source share

Yes. Type B objects contain part A when they are selected. No need to worry about this (namely, no need to highlight B and A).

+1
Oct 06 2018-11-11T00:
source share

When you control B through new B() , an implicit (or explicit) call is made to constructor A. Thus, memory allocation is performed for both classes.

In particular, if A declares three integer members, and B (extends A) declares 2 float members, each new B will highlight three ints and two floats.

+1
Oct. 06 '11 at 9:15
source share



All Articles