匿名内部类是否总是捕获对“this”的引用? (外部)对象在访问其原语等时?
如果我
[编辑:添加了“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();
}
}
对inner.execute()的调用将设置该特定的outerInt
变量em> Outer
对象到 5
,无论从何处调用,只要 Inner
对象存在?或者它只会更改 outerInt
变量的副本,而不影响原始 Outer
对象?
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? Or will it just change a copy of the outerInt
variable and not affect the original Outer
object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这将捕获并修改外部
this
。请参阅规范
This will capture and modify the outer
this
.See the spec
回答您新澄清的问题(从评论到我的其他答案):
是。
所有内部类和本地类都将引用其父类的
this
,即使它们从不使用它。演示。
To answer your newly clarified question (from the comment to my other answer):
Yes.
All inner and local classes will have a reference to their parent's
this
, even if they never use it.Demo.
这不一定是真的。您没有显示的是 Inner 的类声明。如果 Inner 有一个名为outerInt 的字段,那么该字段将被修改。否则Outer的outerInt将会。如果你运行:
你会得到0,而不是5。
但是通过在Inner中注释掉outerInt,那么你会得到5
This is not necessarily true. You didn't show is the class declaration for Inner. If Inner has a field called outerInt, then that one will be modified. Otherwise Outer's outerInt will. If you run:
You will get 0, not 5.
But by commenting out outerInt in Inner, then you get 5
是的,确实如此。但是如果你需要使用外部类的实例,例如传递给某个方法,你必须说Outer.this。
Yes it does. But if you have a need to use outer class's instance, e.g. passing to some method, you have to say Outer.this.