How does Java create an object in the JVM? What happens on the stack and heap when I call the constructor?

Possible duplicate:
Java Instantiation.

Suppose we have a Java class test, this class has two data fields a and b and has a foo () method. When we run "Test t = new Test ()", I want to know the following.

  • what happened on the stack?
  • What happened to the bunch?
  • We have one copy of the class and many instances (objects) at runtime, right? So where is the contents of the class stored? The content of the class is static.
  • On the heap, I think that the data fields a and b should be stored as they are dynamic (specific to a specific object). What about the foo () method? Do I need to store the contents of foo () along with a and b on the heap?

Basically, I want to know the magic of a new keyword?

+6
source share
1 answer

Basically:

  • Any class code (both instance and static methods, static variables, etc.) will be located in what you could call a "program code" area, which is neither a heap nor a stack.
  • The object itself will be built on the heap and will contain instance fields plus a table of pointers to the corresponding instance methods (the so-called vtable) according to inheritance. Note that this object will include every member for every class in the inheritance chain, even if the way you process it does not reveal specific members. (Say, C extends B extends A, and B has a private field, the object C will still contain a B-field, even if it is invisible).
  • Fields and variables will either contain references to objects (mostly transparent pointers), or a native type, such as int, double, or boolean (those that start in lowercase).
  • Local variables and method parameters will be saved on the stack.
0
source

Source: https://habr.com/ru/post/886077/


All Articles