-1

If I have a class, CatFrame, that extends JFrame then I set myCat = new CatFrame(); then later I do myCat = new CatFrame(false);. Is the old CatFrame eligible for garbage collection?

public class CatFrame extends JFrame{
    public CatFrame(){
         this.setVisible(false);
    }

public CatFrame(boolean b){
         this.setVisible(false);
    }
}
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Ian
  • 354
  • 4
  • 13
  • see [Remove Top-Level Container on Runtime](http://stackoverflow.com/questions/6309407/remove-top-level-container-on-runtime) – mKorbel Jun 28 '16 at 19:30

2 Answers2

8

You need to be careful with Swing components that extend Window, like JFrame and JDialog, as they have peer components that will not be garbage collected. To gc a Window properly, use Window.dispose();

But otherwise, once an object on the heap is not reachable from any active thread, that object is eligible for garbage collection

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

Yes. You are replacing "old" CatFrame with the "new" one, thus allowing the "old" CatFrame to be collected by the garbage collector because it is no longer accessible in any way by your program (if that was the only reference).

EDIT:

JFrames and other such objects are little tricky though. See ControlAltDel's answer.

Infamous911
  • 1,441
  • 2
  • 26
  • 41