Small Example
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
If I create a new Leaf
node, and set it as the leaf of the Tree, I know this will update the pointer inside Tree
. My question is, what happens to the old Leaf
object?
If there is no Strong reference being held to the old leaf object in the code, then it is eligible for garbage collection and will be cleaned up by the Garbage Collector.
Example 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
Example 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
Note : A strong reference is a normal Java reference. For more info on different type of references refer the following article -Java - types of references
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With