posted 16 years ago
No. The singleton pattern brings in several other issues which really aren't relevant here. As far as garbage collection is concerned, it doesn't really matter whether a field is public or private. And making the field static - well, that can prevent one object from being collected. However if you create a second object of the same clas, then "a = this" will be executed a second time, and since a is static the reference to the previous "this" object will be lost. So making a static will prevent the most recently created object from being collected, but it won't prevent them all from being collected.
If you really wanted to prevent collection of all objects in a class (and it's a mystery why anyone would ever want to do this), you could do something like this:
Here the collection ensures that all Uncollectable objects will not be collected, because it retains a reference to each one.
(Technically these can still be collected if the class itself is unloaded, which requires that you load the class in the first place using a special ClassLoader, and then make that loader available for collection. That's far outside the scope of what you need for the exam however.)
"I'm not back." - Bill Harding, Twister