开发者

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

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Java Instantiation.

Suppose we have a java class Test, this class has two data fields a and b, and has 开发者_StackOverflow社区a method foo(). When we execute "Test t=new Test()", I wanna know the following things.

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

Basically, I wanna know the magic of the new keyword?


Basically:

  • Any class-shared code (both instance and static methods, static variables, etc) will be located in what you could call the "program code" area, which is neither the heap nor the stack.
  • The object itself will be constructed in the heap, and will comprise the instance fields plus a table of pointers to the proper instance methods (the so-called vtable) according to inheritance. Note that this object will include every member for each class in the inheritance chain, even if the way you're treating it doesn't reveal certain members. (Say, C extends B extends A, and B has a private field, a C object will still contain the B-field, even if it's invisible).
  • Fields and variables will contain either object references (basically transparent pointers) or a native type, such as int, double or boolean (the ones that start in lowercase).
  • Local variables and method parameters will be stored in the stack.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜