[英]Does an anonymous inner class always capture a reference to “this” (outer) object when accessing its primitives etc.?
If I have 如果我有
[EDIT: added the type definition for "Inner"] [编辑:添加“内部”的类型定义]
interface Inner{
public void execute();
}
class Outer{
int outerInt;
public void hello(){
Inner inner = new Inner(){
public void execute(){
outerInt=5;
}
}
//later
inner.execute();
}
}
will the call to inner.execute()
set the outerInt
variable of that particular Outer
object to 5
, wherever it is called from, and for as long as that Inner
object exists? 对
inner.execute()
的调用是否会将该特定 Outer
对象的outerInt
变量设置为5
,无论它在何处被调用,只要该Inner
对象存在? Or will it just change a copy of the outerInt
variable and not affect the original Outer
object? 或者它只是更改
outerInt
变量的副本而不影响原始的Outer
对象?
This is not necessarily true. 这不一定是真的。 You didn't show is the class declaration for Inner.
你没有展示的是Inner的类声明。 If Inner has a field called outerInt, then that one will be modified.
如果Inner有一个名为outerInt的字段,那么将修改该字段。 Otherwise Outer's outerInt will.
否则外面的外部会。 If you run:
如果您运行:
public class Outer {
int outerInt = 0;
public void hello() {
Inner inner = new Inner() {
@Override
public void execute() {
outerInt = 5;
}
};
// later
inner.execute();
System.out.println(outerInt);
}
public static void main(String[] args) {
Outer o = new Outer();
o.hello();
}
}
class Inner {
int outerInt;
public void execute() {
}
}
You will get 0, not 5. 你会得到0而不是5。
But by commenting out outerInt in Inner, then you get 5 但是通过评论Inner的outerInt,你得到5
Yes it does. 是的,它确实。 But if you have a need to use outer class's instance, eg passing to some method, you have to say Outer.this.
但是如果你需要使用外部类的实例,例如传递给某个方法,你必须说Outer.this。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.