What are the reasons behind such design?
(Hint: Stacks)
http://stackoverflow.com/questions/873792/where-is-allocated-variable-reference-in-stack-or-in-the-heap
void myMethod() { Ship myShip = new Ship(); }
Where is allocated myShip reference, in stack or in the heap ?
I think in stack but I'm confused because I was reading in J2ME Game Programming book "Java classes are instantiated onto the Java heap"
Ans:
myShip
is a reference to a Ship
object, it is on the method call stack, which is referred to as "the stack". When a method is called a block of memory is pushed onto the top the stack, that memory block has space for all primitives (int, float, boolean etc) and object references of the method. The heap is where the memory for the actual objects is allocated.
So
myShip
is on the stack and the Ship
object is on the heap.
Note each thread has its own stack but share the heap.
沒有留言:
張貼留言