What happens when an object is dereferenced but its member object is still referenced?

前端 未结 3 1228
暗喜
暗喜 2021-01-16 08:37
class ClassA {
    ClassB mem1 = new ClassB();
    ClassB mem2 = new ClassB();
}

class ClassB {
}

public class Sample {
    public static void main(String[] args)          


        
3条回答
  •  醉酒成梦
    2021-01-16 09:26

    Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

    Java Garbage Collection Basics

    In this context, when obj1 = null; is processed there are no references to the object of type ClassA to which it points, and so it is eligable for garbage collection. The ClassB object, mem1 however still has a reference in the form of obj2 and so is kept at least until the line obj2 = null; is executed.

提交回复
热议问题