Refining the keyword "this" in Java

I have copied this code from the Android developers site:

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 wonder what exactly the keyword "this" refers to. Does this apply to the ExampleActivity class? And anyway, how to find what "this" means?

+4
source share
5 answers

It refers to an instance of ExampleActivity on which onCreate() was called.

In general, from the Java Language Specification, 15.8.3 :

The this keyword can only be used in the body of an instance method, an instance initializer or constructor, or in an initializer of an instance variable of a class. If it appears elsewhere, a compile-time error occurs.

When used as the main expression, the this keyword denotes a value that is a reference to the object for which the instance method has been called (Β§15.12), or to the object that is being created. The type of this class is the class C in which this keyword occurs. At run time, the class of the actual object that can be specified can be class C or any subclass of C.

+4
source

this refers to the innermost instance of the class. In your example, this refers to ExampleActivity , which is of type OnClickListener , which is passed to setOnClickListener .

+2
source

Inside an instance method or constructor, this is a reference to the current object β€” the object whose method or constructor is. You can refer to any member of the current object from an instance method or constructor using this .

Link (from Sun Java Tutorial):

+1
source

"this" is a link to the current object.

In your case, this applies to an instance of the ExampleActivity class.

http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html

+1
source

Yes, 'this' refers to an instance of the surrounding class.

0
source

All Articles