• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner classes and GC

 
Simeon Cherniy
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Neelesh Bodas
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> 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 = test.new 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic