OiR*_*iRc 3 java reference object
小例子
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
Run Code Online (Sandbox Code Playgroud)
如果我创建一个新Leaf节点,并将其设置为树的叶子,我知道这将更新内部的指针Tree.我的问题是,旧 Leaf物体会发生什么?
如果代码中没有对旧叶子对象进行强引用,则它有资格进行垃圾回收,垃圾收集器将对其进行清理.
例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
Run Code Online (Sandbox Code Playgroud)
例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
Run Code Online (Sandbox Code Playgroud)
注意:强引用是普通的Java引用.有关不同类型引用的更多信息,请参阅以下文章 - Java - 引用类型