File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inner classes and GC 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 "Inner classes and GC" Watch "Inner classes and GC" New topic

Inner classes and GC

Simeon Cherniy

Joined: Jul 26, 2006
Posts: 21
Hallo! :-)
I have a question:
Example code:

I read that the object of inner class has "reference" to the object of top level class.

1. What kind of "reference" is it?
2. What does happen after calling System.gc() in code above?
3. Is object of class Test removed from the heap?

Thank you.

P.S. If there are any errors in the code, takes it easy, not as mistake :-)

[ September 17, 2006: Message edited by: Simeon Cherniy ]
[ September 17, 2006: Message edited by: Simeon Cherniy ]

5-year Student of <br />Moscow Institute of Physics and Technology.
Neelesh Bodas
Ranch Hand

Joined: Jul 20, 2006
Posts: 107
> Test test = new Test();

A new Test object is created on the heap. There is one reference that refers to this object. The reference itself is on stack.

> Test.Inner inner = Inner();

A new Inner object is created on the heap. The reference variable "inner" lies on stack and refers to the Inner instance on the heap. The inner object has a reference to the Test object. Thus, note that the heap-based instance of Test has now two references referring to it - one on stack and other from within the instance of Inner.

Also note that the instance of the Test class doesNOT have a reference to the instance of the Inner class.

> test = null;

The stack reference no more refers to anything. Thus, the heap-based instance of Test has only one reference referring to it - the reference through the instance of Inner.

> System.gc();

Neither Inner nor Test instance is eligible for GC - each of them has a reference referring to it.

> inner.print();

Invokes print method on the instance of Inner referenced by the stack-based reference "inner".

As an aside, note that calling a garbage-collector on invoking System.gc() is not guaranteed.
I agree. Here's the link:
subject: Inner classes and GC
It's not a secret anymore!