• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Inner classes and GC

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
And then the entire population worshiped me like unto a god. Well, me and this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic