posted 13 years ago
I change the code like the above.
When e1, e2 and e3 are reference variables that are set to null, the objects created on line a, b , c have no reference variables refering to them. All the Eco e objects encapusulated by those objects created in line a, b, c will be not reachable as there are no other reference variables refering to them.
For example, if I uncomment out line d, the object refered by e1.e reference variable will not be eligible for GC at line e as there is a reference variable a refering to it. In this situation, althought at line e, e1 is eligible for GCed, the object that was referred by e1.e variable is not as a is now refering to it.
In the exam, when dealing with eligible for GC, pay attention to the object itself created in line 1, 2,3 ... and the variable references a, b, c..... For example,
Eco a is not an object itself. Eco a = new Eco(); means creating an object with a reference variable a.
For another example,
Will a be eligible for GC when play() method exits? My answer is No. a is just a variable, that is not initialized. This code still compiles as long as we never use a to invoke any methods in Integer class.
For another example,
public class Test{
Integer a = new Integer("1");
Integer n ;
public static void main (String...args){
System.out.println("Hello world");
}
}
Will Integer a be eligible for GC when main method finishes? My answer is Yes.
Will n be eligible for GC when main method finishes? My answer is No because n is a reference variable and is initialized as null, n never refers to any object.
Correct me if I am wrong.