1

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

4

2 回答 2

11

static嵌套类和非嵌套类之间的区别static恰恰在于非static内部类的实例与封闭类的特定实例相关联,而static内部类则没有。没有关联的内部类的A.this实例。static

于 2013-08-13T16:25:07.537 回答
2

如果是内部类,static则可以在没有外部类的封闭实例的情况下对其进行实例化。对于非static内部类,实例化需要外部类的实例。例如,如果您的类结构是这样的:

public class A {
    public static class B {
    }

    public class C {
    }
}

然后实例化BC你必须这样做:

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

在实例化非内部类的幕后static,将封闭类的实例传递给构造函数。的实例OuterClass.this因此可以访问。

要验证“幕后”的事情,您可以通过反射检查内部类的声明构造函数和声明字段:

// 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);
}
于 2013-08-13T16:34:49.143 回答