Harini
Harini

Reputation: 303

memory allocation for a class in java?

class B inherits class A. Now when we create an object of type B, what is the memory allocated for B? Is it including A and B, or any other procedure for memory allocation?

Upvotes: 3

Views: 5622

Answers (3)

Alex
Alex

Reputation: 301

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

B myObject = new B();

Then the JVM allocates an object with more or less:

  • Enough memory for every field explicitly declared in B (usually around 4-8 bytes per field, but it varies a lot from types and the host system)
  • Enough memory for every eventual field inherited by A and its ancestors
  • Enough memory to contain a reference to the dispatch vector (which should be around 4-8 bytes too)

The dispatch vector is used by the compiler to store the address of every method that can be invoked on the given object and it depends on the class of the object rather than the instance of the object itself (every object B has the same interface after all!)

So you do NOT need to allocate A, because there's no separate object A. You aren't instancing 2 separate objects. When you create B you are creating a "specialized" version of A.. which it can be viewed as A with something more. So only B needs to be allocated (but keep in mind that B also has everything its ancestors have)

Upvotes: 3

solendil
solendil

Reputation: 8458

When you instanciate a B through new B(), an implicit (or explicit) call is made to the constructor of A. The memory allocation is thus done for both classes.

More specifically, if A declares three integer members and B (extends A) declares 2 float members, each new B will allocate three ints and two floats.

Upvotes: 1

Eran
Eran

Reputation: 22030

Yes. Objects of type B contain the part of A when they are allocated. No need to worry about that (namely no need to allocate both B and A).

Upvotes: 1

Related Questions