Вопрос

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!

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top