Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to old Object references?

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?

like image 836
OiRc Avatar asked Mar 19 '23 16:03

OiRc


1 Answers

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

like image 63
Kakarot Avatar answered Mar 22 '23 06:03

Kakarot