问题描述
我有一个问题
例如,当我在方法中声明变量时,会发生什么。
void myMethod(){
Ship myShip = new Ship();
}
在堆栈或堆中分配myShip引用的位置?
我认为在堆栈,但我很困惑,因为我正在阅读J2ME游戏编程书
Java类被实例化到Java堆
运输
对象的引用, myShip
方法调用堆栈,称为堆栈。当一个方法被调用时,一个内存块被推到堆栈顶部,该内存块具有所有原语(int,float,boolean等)和方法的对象引用的空间,包括方法参数。堆是为实际对象分配内存的地方。 所以 myShip
在堆栈上, Ship
对象在堆上。
注意每个线程都有自己的堆栈,但共享堆。
I have a question
What happend when I declare a variable inside a method, for example.
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"
All java clases ?
Thanks in advance
myShip
is a reference to a Ship
object, myShip
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, which includes the method parameters. 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.
这篇关于在哪里分配变量引用,在堆栈还是在堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!