这个问题是基于 Thinking in Java,第 2 版,第 109 页 的 Scope of Object 一章,它说当我们使用 创建 Java 对象时新的 它在范围末尾徘徊。它给出了这个例子:
{
String s = new String("a string");
} /* end of scope */
然后它说,
the reference s vanishes at the end of the scope. However, the String object that s was pointing to is still occupying memory. In this bit of code, there is no way to access the object because the only reference to it is out of scope.
所以如果我理解正确的话,文本“a string”仍然存在于内存中,但是具有第一个字符“a”的内存地址的指针不存在。是这个意思吗?
接着说,
It turns out that because objects created with new stay around for as long as you want them, a whole slew of C++ programming problems simply vanish in Java.
为什么这是有利的?在上面的示例中,字符串数据继续驻留在内存中,无法访问它(因为指针在超出范围后被销毁),这只会消耗资源。
最佳答案
简单的说,引用变量s
在段中的作用域:
{
String s = new String("a string");
} /* end of scope */
在大括号之间。这意味着 s
仅存在于开始和结束 {} 之间。然而,那个街区发生了一些事情。
在大括号内,调用new
运算符来创建String
对象的实例。为对象分配内存,并将对它的引用分配给变量 s
。
在代码块的末尾,s
不再存在,因此它持有的引用也不再存在。然而,String
对象仍然存在于内存中。但是由于不再有任何变量持有对它的引用,因此程序的任何部分都不再可以访问它。此时,该对象符合垃圾回收条件。
在一个对象被垃圾回收之前,它仍然在系统内存中占据一个位置,即使它不再被程序访问。
关于java - 不懂java中对象的作用域(java新手困惑),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17647194/