在Java中,当我们只声明一个类类型的变量时,只会创建一个引用(不会为对象分配内存)。是将引用 t 保存在将在堆上创建空间的某个地方吗?或者,如果我错了,那么当我们只声明变量时,内存中到底发生了什么?
Test t;
最佳答案
In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object).
这是正确的。
Is to hold the reference t somewhere space will be created on heap?
答案取决于声明出现的上下文。如果所述声明是对象的一部分(即 t
是一个 field),那么引用的空间将从堆中分配,以及其余的空间包含字段的对象。否则,将在 JVM 的栈帧中分配引用空间。
关于java - 仅声明类类型变量时的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206641/