Java Anonymous Class and Available Private Variable

interface Test {
public void test();
}

public class TestMain {
private String h = "AAA";

public static void main(String[] args) {
    TestMain t = new TestMain();
}

public TestMain() {
    Test t = new Test() {
        public void test()  {
            System.out.println( h );
        }
    };

    t.test();
}

}

This source works well.

But I think the variable "h" should be inaccessible from an anonymous class. I need to know why this works.

Thanks for your help in advance!

+5
source share
3 answers

Each instance of a non-static inner class has an enclosing instance - an instance of the outer class that it binds to it through a reference variable stored in the inner object of the class. All members of the incoming instance are accessible to the internal class object via this link.

, , , , . , javap -c.

+7

, 6.6.1 Java:

[I] f , , , .

+1

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the surrounding class.

-1
source

All Articles