旧的Object引用会发生什么?

时间:2014-05-08 21:26:32

标签: java object reference

小例子

Class Tree{
    private Leaf leaf;

    public Tree(Leaf leaf){  //passing a object that is instantiated outside the class
        this.leaf = leaf;       
    }

    public void foo(){
         Bush bush = new Bush(leaf);
    }

    public setLeaf(Leaf leaf){
        this.leaf = leaf;    
    }
}

class Forest{
    private Tree tree;

    public Forest(Tree tree){
        this.tree = tree;

    }     
    public void doSometing(){
        Leaf leaf = new Leaf();
        tree.setLeaf(leaf);
    }

}

//code to initialize objects described above

如果我创建一个新的Leaf节点,并将其设置为树的叶子,我知道这将更新Tree内的指针。我的问题是, Leaf对象会发生什么?

1 个答案:

答案 0 :(得分:5)

如果代码中没有对旧叶子对象进行强引用,则它有资格进行垃圾回收,垃圾收集器将对其进行清理。

示例1:

Employee emp1 = new Employee("John Doe"):

emp1 = new Employee("John");  
// There is no strong reference to previously created Employee Object
// So its eligible for garbage collection

示例2:

 Employee emp1 = new Employee("John Doe"):
 emp2 = emp1;

 emp1 = new Employee("John");  
 // In this case emp2 hold a strong reference to previously created Object
 // so its not eleigible for Garbage collection

注意:强引用是普通的Java引用。有关不同类型参考文献的更多信息,请参阅以下文章 - Java - types of references