This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
class OuterClass { int i; void printInstanceVaraibles() { System.out.println("I value "+ i); } class InnerClass { int j; void printInstanceVariables() { System.out.println("J value " + j); } } }
class Main { public static void main(String args[]) { OuterClass outerClass = new OuterClass(); InnerClass innerClass = outerClass.new InnerClass(); outerClass = null; //GC } }
AT //GC howmany objects are eligible for Garbage Collection?
Remko Strating
Ranch Hand
Joined: Dec 28, 2006
Posts: 893
posted
0
I think the answer is zero, because the innerclass holds a reference to the outerclass.
can anybody explain? it is really a good question.
Sourin K. Sen
Ranch Hand
Joined: May 02, 2006
Posts: 85
posted
0
See the answer to this question would seem to be pretty simple if you can understand one basic thing :
inner class's object cannot exist without an instance of the outer class (except for static inner classes which aren't inner classes anyways).
In this case, since inner class has got a reference which is alive, it also means that the instance of outer class is stored safely in inner (we might say as such) because the inner class may need to access the instance members of the outer class & for that it should have a reference to the outer class's object.
Now since the inner class IS referring to the outer class implicitly, it means that there is a reference for the outer class (which we cannot access by the way) & hence no question of the outer class's object being garbage collected.
Note "rami reddy marri" : the statement InnerClass innerClass = outerClass.new InnerClass(); is invalid.
Please change it to : OuterClass.InnerClass innerClass = outerClass.new InnerClass(); [ March 23, 2007: Message edited by: Sourin K. Sen ]