Why can't a static nested class access “this” pointer of outer class?

半世苍凉 提交于 2019-12-11 04:47:27

问题


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?"


回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/18214290/why-cant-a-static-nested-class-access-this-pointer-of-outer-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!