Please explain “this” to me

前端 未结 6 1355
轮回少年
轮回少年 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:18

    this refers to the current Object's reference.

    Read this for more understanding.

    To give an example from the link:

    public class Point {
        public int x = 0;
        public int y = 0;
    
        //constructor
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    

    Here, to differentiate from the x of the Point and x of the argument, you need to tell the compiler the difference. You achieve that using this. Meaning, when I write, this.x it means, the particular x belongs to the current Object, which in the case is Point.

    Taking example from the code that you have provided:

    AlertDialog.Builder(this)
    

    AlertDialog.Builder() takes in a Context as a parameter in its constructor. But here, you don't do Context someContext = new Context(); and pass that as the parameter, because you simply need to pass your current Activity's Context. So you simply use this.

提交回复
热议问题