[英]Why can't a static nested class access “this” pointer of outer class?
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. 我认为这可能与“ this”指针不是静态的,因此内部类无法访问它有关。 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?" 这对我也提出了另一个问题,即“在哪里定义了“ this”指针?”
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. 一个之间的差
static
嵌套类和一个不是static
恰恰是一个非的一个实例static
内部类与封闭类的特定实例相关联,而一个static
内部类是没有的。 There is no A.this
for an instance of a static
inner class to be associated with. 没有
A.this
要的实例static
内部类要与之关联。
If an inner class is static
then it can be instantiated without an enclosing instance of the outer class. 如果内部类是
static
则可以实例化它而无需包含外部类的实例。 For a non- static
inner class an instance of the outer class is required for instantiation. 对于非
static
内部类,实例需要外部类的实例。 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 : 然后要实例化
B
和C
您必须像这样:
// 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. 当实例化非
static
内部类时,在幕后将封闭类的实例传递给构造函数。 The instance of OuterClass.this
is then accessible because of this. 因此,可以访问
OuterClass.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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.