简体   繁体   English

需要帮助了解未引用的对象

[英]Need Help Understanding Unreferenced Object

I was learning about objects on the Java Oracle tutorials and I learned how to reference an objects fields. 我在Java Oracle教程中学习了有关对象的知识,并且学习了如何引用对象字段。 They gave me two ways to do it, and the the first method I understood. 他们给了我两种实现方法,第一种是我理解的方法。 However, the second method of doing it confused me. 但是,第二种方法使我感到困惑。 This is the code: 这是代码:

int height = new Rectangle().height;

I understand the statement itself, but it is what the tutorial says that confused me. 我理解声明本身,但这就是本教程所说的使我感到困惑的地方。 The tutorial said "This statement creates a new Rectangle object and immediately gets its height. In essence, the statement calculates the default height of a Rectangle. Note that after this statement has been executed, the program no longer has a reference to the created Rectangle, because the program never stored the reference anywhere. The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine. But wait wasn't it referenced with the variable name "height"? So how is it unreferenced? I understand this: 教程说:“此语句创建一个新的Rectangle对象并立即获取其高度。本质上,该语句计算Rectangle的默认高度。 请注意,执行此语句后,程序不再引用创建的Rectangle ,因为该程序从未在任何地方存储引用。该对象是未引用的,并且它的资源可以由Java虚拟机免费回收,但是请问它不是用变量名“ height”引用的吗?我了解这一点:

Rectangle rect1 = new Rectangle(1,2,3);// random arguements don't mind them

So what makes this line of code referenced but the other unreferenced? 那么,是什么使这一行代码被引用而另一行未被引用呢?

I think you are trying to read it too literally. 我认为您正在尝试从字面上读它。

But wait wasn't it referenced with the variable name "height"? 但是等等它不是用变量名“ height”引用的吗? So how is it unreferenced? 那么它如何未被引用?

You could say that an anonymous reference was created and well... referenced once to get the height. 您可以说已经创建了一个匿名引用,并且...引用一次即可获得高度。

Note that after this statement has been executed, the program no longer has a reference to the created Rectangle, because the program never stored the reference anywhere. 请注意,执行此语句后,程序不再具有对创建的Rectangle的引用,因为该程序从未将引用存储在任何地方。 The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine. 该对象是未引用的,并且其资源可以由Java虚拟机免费回收。

Since the reference is anonymous it cannot be used anywhere else. 由于引用是匿名的,因此无法在其他任何地方使用。 Hence after that statement there is no way to reference the object. 因此, 在该语句之后,无法引用该对象。 If so then why keep it in memory - it may as well be garbage collected. 如果是这样,那么为什么将其保留在内存中-最好也将其收集为垃圾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM