当父对象这样做时,作为另一个对象成员的对象是否有资格进行垃圾收集?例如,让我们想象一下这种情况:
MyClass_1 的代码:
public class MyClass_1 {
// Member object
private MyClass_2 myClass_2;
// Getter
public MyClass_2 getMyClass_2() {
return this.myClass_2;
}
// Setter
public void setMyClass_2(MyClass_2 myClass_2) {
this.myClass_2 = myClass_2;
}
}
MyClass_2 的代码:
public class MyClass_2 {
// Member object
private MyClass_3 myClass_3;
// Getter
public MyClass_3 getMyClass_3() {
return this.myClass_3;
}
// Setter
public void setMyClass_3(MyClass_3 myClass_3) {
this.myClass_3 = myClass_3;
}
}
好的,现在我们做(MyClass_3 的代码不相关):
// Instantiation of one root object
MyClass_1 object_1 = new MyClass_1();
// Composition of two more objects
object_1.setMyClass_2(new MyClass_2());
object_1.getMyClass_2().setMyClass_3(new MyClass_3());
// And now...
object_1 = null;
当然,此时object
_1 是 Garbage Collectable,但又如何呢object_2
?object_3
呢?我应该这样做以避免内存泄漏吗?
object_1.getMyClass_2().setMyClass_3(null);
object_1.setMyClass_2(null);
object_1 = null;
或者 JVM 会自动执行该参考版本吗?如果需要手动完成,我可以依靠 finalize() 来达到这个目的吗?