Why must I use the “this” keyword for forward references?

后端 未结 5 2045
孤街浪徒
孤街浪徒 2020-12-24 05:11

When I use the this keyword for accessing a non-static variable in a class, Java doesn\'t give any error. But when I don\'t use it, Java gives an error. Why mus

5条回答
  •  萌比男神i
    2020-12-24 05:11

    You have presented 3 cases:

    1. int a = b; int b;
      This gives error because the compiler will look for b in the memory and it will not be there. but when you use this keyword then it specifies explicitly that the b is defined in the scope of the class, all class references will be looked up for it, and finally it will find it.
    2. Second scenario is pretty simple and as I described, b is defined in the scope before c and will not be a problem while looking for b in the memory.
    3. int var1 = this.var2;
      int var2 = this.var1;
      In this case no error because in each case the variable is defined in the class and assignment uses this which will look for the assigned variable in the class, not just the context it is followed by.

提交回复
热议问题