Why can't a static nested class access “this”

2019-08-14 08:08发布

enter image description here

The thing that bothers me is the second point.

I thought it might have to do with the fact that the "this" pointer isn't static and so the inner class can't access it. I'm not sure if that's the right explanation though.

This also raised another question for me which was "where is the "this" pointer defined?"

2条回答
疯言疯语
2楼-- · 2019-08-14 08:51

The difference between a static nested class and one that isn't static is precisely that an instance of a non-static inner class is associated with a specific instance of the enclosing class, while a static inner class isn't. There is no A.this for an instance of a static inner class to be associated with.

查看更多
我命由我不由天
3楼-- · 2019-08-14 08:54

If an inner class is static then it can be instantiated without an enclosing instance of the outer class. For a non-static inner class an instance of the outer class is required for instantiation. For example, if your class structure is this :

public class A {
    public static class B {
    }

    public class C {
    }
}

then to instantiate B and C you would have to do it like this :

// simply
A.B b = new A.B();
// however
A.C c = new A().new C();

Behind the scenes when a non-static inner class is instantiated an instance of the enclosing class is passed into the constructor. The instance of OuterClass.this is then accessible because of this.

To verify the "behind the scenes" thing you can check the declared constructors and declared fields of the inner class via reflection:

// prints that there is one field of type A called "this$1"
for (Field f : A.C.class.getDeclaredFields()) {
    System.out.println(f);
}

// prints that the constructor takes in one parameter of type A
for (Constructor c : A.C.class.getDeclaredConstructors()) {
    System.out.println(c);
}
查看更多
登录 后发表回答