Please explain “this” to me

前端 未结 6 1359
轮回少年
轮回少年 2021-01-01 05:03

I\'ve read hundreds of explanations on \"this\" in java and I\'m really having trouble grasping it. I\'m learning android and java side-by-side, I know it\'s harder that wa

6条回答
  •  旧巷少年郎
    2021-01-01 05:25

    The keyword this, like others have said, is just a reference to the current object. This is usually implicit, such that if you have a class as so:

    class ThisExample{
        int x;
        public ThisExample(int x){
            this.x = x;
            someMethod();
            this.someMethod();
        }
    
        void someMethod()
        {
        ...
        }
    }
    

    Using this.x = x helps to differentiate between the member variable owned by the class and the variable being passed into the constructor. Also, calling this.someMethod() and someMethod() does exactly the same thing because the this is implied.

    In Android, sometimes you will see a method with this being passed in like someMethod(this). What happens here is that this is referring to the current Activity's Context, which is just a bunch of information explaining everything about the Activity.

提交回复
热议问题