File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage collection in Inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage collection in Inner classes" Watch "Garbage collection in Inner classes" New topic
Author

Garbage collection in Inner classes

Ram Reddy
Ranch Hand

Joined: Feb 20, 2007
Posts: 88
Hi ,

if code as follows

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
I think the answer is zero, because the innerclass holds a reference to the outerclass.


Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
Srinivas Kumar
Ranch Hand

Joined: Jul 14, 2005
Posts: 52
can anybody explain? it is really a good question.
Sourin K. Sen
Ranch Hand

Joined: May 02, 2006
Posts: 86
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 ]

Regards,<br />Sourin.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Garbage collection in Inner classes