Java对象如何存储在内存中?

在Java中,所有对象都是在堆上动态分配的。这与C++在堆栈或堆上可以分配对象的不同。在C++中,当使用New()分配对象时,对象将在堆上分配,否则将在堆栈上分配,而不是全局或静态。 在Java中,当我们只声明一个类类型的变量时,只创建一个引用(不为对象分配内存)。为了给对象分配内存,我们必须使用new()。因此对象总是在堆上分配内存(参见 更多细节)。 例如,以下程序在编译中失败。编译器给出错误 “此处出错,因为t未初始化”。

null

JAVA

class Test {
// class contents
void show()
{
System.out.println( "Test::show() called" );
}
}
public class Main {
// Driver Code
public static void main(String[] args)
{
Test t;
// Error here because t
// is not initialized
t.show();
}
}


使用new()分配内存使上述程序工作。

JAVA

class Test {
// class contents
void show()
{
System.out.println( "Test::show() called" );
}
}
public class Main {
// Driver Code
public static void main(String[] args)
{
// all objects are dynamically
// allocated
Test t = new Test();
t.show(); // No error
}
}


如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享