clarification of “this” keyword in Java

让人想犯罪 __ 提交于 2019-12-01 19:15:57

It refers to the instance of ExampleActivity on which onCreate() has been called.

In general, from the Java Language Specification, 15.8.3:

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.

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.

this refers to the most inner class instance. In your example it refers to ExampleActivity which is of type OnClickListener which is passed in to setOnClickListener.

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Reference (from the Sun Java Tutorial):

"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

Yes, 'this' refers to the instance of the enclosing class.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!