clarification of “this” keyword in Java

后端 未结 5 1269
陌清茗
陌清茗 2021-01-19 15:17

I have this code copied from Android developers website:

public class ExampleActivity extends Activity implements OnClickListener {
    protected void onCrea         


        
5条回答
  •  孤独总比滥情好
    2021-01-19 15:54

    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.

提交回复
热议问题