简体   繁体   中英

is object of outer class must be in memory as long as object of local inner class(local to a method) in memory in java?

Because Local Inner class can reference outer class member variables. If local inner class object is to be used outside the method (may be outside the class). Outer class Object's memory must not be marked as garbage. How memory is managed for Local inner class object ?

`

package inner;

interface A {
    int x = 123;

    public void print();
}

public class B {
    static A lict;
    static int z = 890;

    public static void main(String[] args) {
        final int y = 90;
        class C implements A {
            public void print() {
                System.out.println("X = " + x + " Y = " + y + " Z = " + z);
            }
        }

        lict = new C();
        B lic = new B();
        lic.printInnerClass();
    }

    public A printInnerClass() {
        lict.print();
        return lict;
    }
}

class D {
    A a;

    public void method() {
        B b = new B();
        a = b.printInnerClass();
    }
}

`

All inner classes, anonymous or not, will have a reference to the outer class and keep it from being garbage collected unless the inner class is declared static.

This is not possible for the case of anonymous inner classes, so yes any class defined in method "Anonymous" will have reference to the outer class.

C does not have a reference to instance of B because it is declared in a static method. So it will not prevent instance of B of GCing

The instance of the inner class maintains a reference to the parent object from which it was created. You can access it from within the inner class as B.this . The GC won't collect the object until all instances of the inner class also go out of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM