You cannot just call the clone method. You need to implement java.lang.Cloneable interface for the class whose object you are going to clone. There are lot of discussions before regarding using clone method. You can search for the same.
Clone method gives you an entirely new object with the values of the instance variables being taken from the instance from which it was cloned.
And what ever be the way the object has been created- Clone or new- If its local object- It will be eligible for GC soon after the method completes its execution provided the object reference has not been returned to the calling method.
Suma Rangaraj wrote:
Say you create an object locally in a method but you only hold a reference to one of it's member variable's even after you are out of the method,
will the local object be GC'd ?
Based on your example, yes, the A object will be eligible for GC once the method goes out of scope. The string array object, that was originally referenced by the A object, is still reachable, and will not be eligible for GC though.
Yes, the local object becomes eligible for garbage collection. I'm going to restate the problem, so you can check that I understand what you mean.
Any object of class A contains a reference to an object B, held in an instance variable.
In object C, you create a new object A, referred to in a local variable, and from A obtain a reference to its object B. It holds this reference in an instance variable of C.
At this point, object C has a (local var) reference to A and a(n instance var) reference to B. The fact that one of them is also referred to by the other doesn't make a lot of difference to C in terms of memory management.
Once the method returns, the local variable reference to A, and therefore that instance of A itself, is eligible for garbage collection. The reference that that instance of A has to B will be freed up along with the rest of the object. However, there will still be a different reference to B, namely the one held in C, and so B is not eligible for collection, because B still has (at least) one reference while that instance of C is referenced somewhere.