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

前端 未结 3 1203
暗喜
暗喜 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

    After obj1 is no longer referenced, it becomes eligible for garbage collection. mem1 still has a reference, so if java were to garbage-collect at this point, obj1 and mem2 it points too would be freed, but mem1 would remain untouched as obj2 still points to it.

    Of course, after obj2 = null, it can also be collected.

提交回复
热议问题