澄清“这个” Java中的关键字 [英] clarification of "this" keyword in Java
问题描述
我从Android开发者网站复制了此代码:
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
}
...
}
我想知道this关键字到底是什么意思至?它是指ExampleActivity类吗?一般来说如何找到this指的是什么?
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?
推荐答案
它指的是的实例ExampleActivity
已调用 onCreate()
。
一般情况下,来自 Java语言规范,15.8.3 :
关键字this只能在实例方法,实例初始化器或构造函数的主体中使用,或者在类的实例变量的初始化器中使用。如果它出现在其他任何地方,则会发生编译时错误。
The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.
当用作主表达式时,关键字this表示一个值,该值是对调用实例方法的对象的引用(第15.12节),或者是正在建造的物体。其类型是C类,其中出现关键字。在运行时,引用的实际对象的类可以是C类或C的任何子类。
When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed. The type of this is the class C within which the keyword this occurs. At run time, the class of the actual object referred to may be the class C or any subclass of C.
这篇关于澄清“这个” Java中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!