Reputation: 303
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
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:
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
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
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