0

I have this situation. After the line c = null; in Example's main method, will the Collar object be bait for Garbage collection ?

Example.java is :

class Example{
    public static void main(String[] args){
        Collar c = new Collar();
        Kit k = new Kit(c);
        c = null;
        //more code to keep the program running

    }
}

Kit.java is :

class Kit{    
    Collar kit_col;
    public Kit(Collar col){
        kit_col = col;
    }
}

Collar.java is :

class Collar{
    public Collar(){
        //nothing here
    }
}
Darshan Chaudhary
  • 2,093
  • 3
  • 23
  • 42
  • 1
    Since `Kit` still refers to your `Collar` object, no. Until `k` goes out of scope, that instance of `Kit` is visible, therefore the `Collar` instance it references is visible too. Objects are only collected when there is no reasonable way to access them. – biziclop Dec 04 '15 at 17:02
  • @biziclop, imagine a case where there are no references to an object at all, but the object in question has a lot of reference to other objects. Can it be GCed then ? – Darshan Chaudhary Dec 08 '15 at 17:45

1 Answers1

1

If you have a reference to your Kit instance, and the Kit instance has a reference to your Collar instance, then neither one can be garbage collected. You still essentially have references to both.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • This has to do with `passing by value is passing by copy`, right ? The variable `c` and `kit_col` aren't tied together in any way other than just pointing to the same object on the heap. True? – Darshan Chaudhary Dec 04 '15 at 17:05