对“这个”的澄清Java中的关键字
我从 Android 开发者网站复制了这段代码:
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
我想知道“this”关键字到底指的是什么?它是否引用“ExampleActivity”类?一般来说,如何找到“this”所指的内容?
I have this code copied from Android developers website:
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
I am wondering what exactly "this" keyword refers to? Does it refer to the class "ExampleActivity"? And in general how to find what "this" refers to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它指的是已调用
onCreate()
的ExampleActivity
实例。一般来说,来自 Java 语言规范,15.8.3:
It refers to the instance of
ExampleActivity
on whichonCreate()
has been called.In general, from the Java Language Specification, 15.8.3:
this
指的是最内部类实例。在您的示例中,它引用ExampleActivity
,其类型为OnClickListener
,并传递给setOnClickListener
。this
refers to the most inner class instance. In your example it refers toExampleActivity
which is of typeOnClickListener
which is passed in tosetOnClickListener
.参考(来自 Sun Java 教程):
会员
Reference (from the Sun Java Tutorial):
Members
“this”是对当前对象的引用。
在您的情况下,它指的是ExampleActivity 类的实例。
http://download.oracle.com/javase/tutorial/java/javaOO /thiskey.html
"this" is a reference to the current object.
In your case, it refers to an instance of the ExampleActivity class.
http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
是的,“this”指的是封闭类的实例。
Yes, 'this' refers to the instance of the enclosing class.