clarification of “this” keyword in Java

2019-02-23 15:11发布

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?

标签: java this
5条回答
干净又极端
2楼-- · 2019-02-23 15:52

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

查看更多
三岁会撩人
3楼-- · 2019-02-23 15:54

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):

查看更多
The star\"
4楼-- · 2019-02-23 15:55

"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

查看更多
劳资没心,怎么记你
5楼-- · 2019-02-23 16:07

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.

查看更多
放荡不羁爱自由
6楼-- · 2019-02-23 16:13

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.

查看更多
登录 后发表回答