访问内部类中的外部类变量 [英] Accessing outer class variable in inner class
问题描述
在内部类中,可以访问外部类的变量,但不能访问方法的局部变量.我了解关于方法的局部变量不可访问的部分,但我想知道为什么外部类变量可访问?
我的理解是,由于内部类与外部类绑定,因此只要父级可用,子级就可以访问其父级变量.我说得对吗?
假定您的外部类称为Outer
,从内部类的范围(非静态)开始,为Outer.this.foo
./p>
例如,
Outer.this.foo=new ArrayList<>();
其中Outer是类的名称,而foo
标识该字段.
您也可以直接将其捕获为foo=new Baz()
,但是如果由于阴影而导致命名冲突,它将选择内部字段.
如果它是静态内部类,则需要一个显式实例:
outerInstance.foo=new ArrayList<>();
或者如果要访问的字段是静态的,请照常使用以下命令进行访问:
Outer.staticFoo=new ArrayList<>();
In inner classes, variables of outer class are accessible, but local variables of a method are not. I understood the part about local variables of a method not being accessible but I want to know why outer class variables are accessible?
My understanding is that as an inner class binds with the outer class, so as long as the parent is available, the child can access its parent variables. Am I correct?
Assuming your outer class is called Outer
, from the scope of the inner class(non-static), Outer.this.foo
to get at the field.
For example,
Outer.this.foo=new ArrayList<>();
where Outer is the name of the class and foo
identifies the field.
You can also grab it directly as foo=new Baz()
but it'll pick the inner field if there's a naming conflict due to shadowing.
if it's a static inner class, you need an explicit instance:
outerInstance.foo=new ArrayList<>();
or if the field to access is static, access it as usual with:
Outer.staticFoo=new ArrayList<>();
这篇关于访问内部类中的外部类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!