[英]Does it refer to the same object or not when an object is passed as an argument of the constructor of another class?
So I came across some confusing code like this.所以我遇到了一些像这样令人困惑的代码。
public class Class1 {
private Class2 class2 = new Class2(this);
public void dispose() {
if (class2 != null) {
class2.dispose();
}
if (class2 != null) {
class2.dispose();
class2 = null;
}
}
}
public class Class2 {
private Class1 class1;
private Class3 class3 = new Class3();
public Class2(Class1 class1) {
this.class1 = class1;
}
public void dispose() {
if (class3 != null) {
class3 = null;
}
class1 = null;
}
}
This is just an extract of what is important to this question from the actual classes.这只是实际课程中对这个问题重要的部分的摘录。 I know the way this code is written is not correct but it is like this.
我知道这段代码的编写方式不正确,但就是这样。
Instance of Class1 is passed on to the constructor of Class2 & kept as a class variable, while the instance of Class1 keeps the instance of Class2 as a class variable. Class1 的实例被传递给 Class2 的构造函数并保存为 class 变量,而 Class1 的实例将 Class2 的实例保存为 class 变量。
When dispose() method is called in Class1, it calls the dispose method in Class2, and in the dispose method of Class2 it assigns null to the Class1 variable it has kept there.当在 Class1 中调用 dispose() 方法时,它会调用 Class2 中的 dispose 方法,并在 Class2 的 dispose 方法中将 null 分配给它保存在那里的 Class1 变量。
This code does not produce an error and executes all the lines in the dispose() method of Class1.此代码不会产生错误并执行 Class1 的 dispose() 方法中的所有行。
Aren't the instance of Class1 that is being nullified by the dispose method in Class2, and the instance of Class1 calling the dispose() on Class2, the same?被Class2中的dispose方法无效化的Class1的实例和Class2上调用dispose()的Class1的实例不一样吗?
It sounds like you don't understand the difference between the concept of objects on the heap and references "pointing" to objects .听起来您不了解堆上对象的概念与“指向”对象的引用之间的区别。 In your example, there are two objects that get created, as there are two calls to
new whatever()
.在您的示例中,创建了两个对象,因为有两个对
new whatever()
的调用。
You can have multiple references pointing to those two objects, but setting a reference to null
does not "delete" (or dispose) the actual object on the heap.您可以有多个指向这两个对象的引用,但设置对
null
的引用不会“删除”(或处置)堆上的实际 object。
Meaning: the objects continue to exist, as long as the garbage collector considers them "alive".含义:对象继续存在,只要垃圾收集器认为它们“活着”。 As the given example is incomplete, it is not possible to determine the overall "alive" state of the different objects.
由于给定的示例不完整,因此无法确定不同对象的整体“活跃”state。 Well, the
Class2
instance is no longer referenced, so that one is eligible to be collected by the garbage collector.好吧,
Class2
实例不再被引用,因此有资格被垃圾收集器收集。 But we don't know how you created the actual instance of Class1
that your test would need.但是我们不知道您是如何创建测试所需的
Class1
的实际实例的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.