1

I have written a simple program that demonstrates garbage collection. Here is the code :

public class GCDemo{

public static void main(String[] args){
    MyClass ob = new MyClass(0);
    for(int i = 1; i <= 1000000; i++)
        ob.generate(i);
}

/**
 * A class to demonstrate garbage collection and the finalize method.
 */
class MyClass{
    int x;

    public MyClass(int i){
        this.x = i;
    }

    /**
     * Called when object is recycled.
     */
    @Override protected void finalize(){
        System.out.println("Finalizing...");
    }

    /**
     * Generates an object that is immediately abandoned.
     * 
     * @param int i - An integer.
     */
    public void generate(int i){
        MyClass o = new MyClass(i);
    }
}

}

However, when I try to compile it, it shows the following error :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    No enclosing instance of type GCDemo is accessible. Must qualify the allocation with an enclosing instance of type GCDemo (e.g. x.new A() where x is an instance of GCDemo).

    at GCDemo.main(GCDemo.java:3)

Any help? Thanks!

JavaNewbie_M107
  • 2,007
  • 3
  • 21
  • 36
  • Possible duplicate of [Java - No enclosing instance of type Foo is accessible](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – fabian Mar 04 '16 at 00:45

2 Answers2

2

Make MyClass static:

static class MyClass {

Without this, you'll have to have an instance of GCDemo in order to instantiate MyClass. You don't have such an instance since main() itself is static.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

You can simplify your example quite a bit. This will do the same thing except you will be sure to see the message. In your example, the GC might not run so you might not see anything befor ethe program exits.

while(true) {
  new Object() {
    @Override protected void finalize(){
      System.out.println("Finalizing...");
    }
  Thread.yield(); // to avoid hanging the computer. :|
}

The basic problem is that you nested class needs to be static.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • The problem is that printing to the screen is very, very slow but creating objects is much quicker which means that you can procude objects faster than they get cleaned up. – Peter Lawrey Dec 14 '12 at 13:07