Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is physical memory organized between base and derived class instances in Java?

Tags:

java

oop

When a subclass C is instantiated, it's known that the constructors of its super classes (say A, and B (B extends A)) will be instantiated earlier than C. So does this mean that:

  1. There are separate memory allocated for A's instance, B's instance and C's instance?
  2. For the instance of subclass C, does it have all the physical memory allocated for the fields inherited from B and A, in addition to its own fields?
  3. and so does B's instance has the physical memory for the fields inherited from A in addition to its own?
like image 489
monica Avatar asked Dec 16 '12 01:12

monica


Video Answer


2 Answers

... it's known that the constructors of its super classes (say A, and B (B extends A)) will be instantiated ...

Classes are instantiated. Constructors are invoked.

(It was suggested in an edit that this should be "Objects are instantiated"; however, this isn't technically correct. Per the same JLS section linked below: "A new class instance is explicitly created when evaluation of a class instance creation expression causes a class to be instantiated." I.e. you instantiate a class in order to get an object. An object is an instance. You don't instantiate objects.)

1) There are separate memory allocated for A's instance, B's instance and C's instance?

No, there is an instance of the class. I.e. one piece of memory.

2) For the instance of subclass C, does it have all the physical memory allocated for the fields inherited from B and A, in addition to its own fields?

Yes: "Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden."

3) and so does B's instance has the physical memory for the fields inherited from A in addition to its own?

As per 1, there is no "B's instance" in this scenario. There's only the one instance.

Source: 12.5. Creation of New Class Instances, JLS 7

like image 157
Ryan Stewart Avatar answered Sep 17 '22 12:09

Ryan Stewart


  1. Only one instance is allocated.
  2. That instance contains all the fields for all classes.
  3. Well, the one and only C instance has the memory for the fields inherited from A and B.
like image 30
Louis Wasserman Avatar answered Sep 19 '22 12:09

Louis Wasserman