java - 不懂java中对象的作用域(java新手困惑)

标签 java

这个问题是基于 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/

相关文章:

java - 发送信号。 PID : 6939 SIG: 9 with zxing QR code scanner

java - 尝试创建并写入文件,但收到错误消息

java - 从其他 Java 类调用方法

java - 针对特定文件的 WinRAR 命令

Java HTML 解析库,无需 HTML 修复

java - 直接从字符串创建流

java - 如何正确销毁一个Spring配置类

java - 在 JTextPane 中换行后插入选项卡

java - 使用 Jython 访问 Java 中 Python 类的公共(public)属性

java - JAAS/JAAC、DROOLS 或自定义