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
You have presented 3 cases:
int a = b;
int b;
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. b
is defined in the scope before c
and will not be a problem while looking for b
in the memory.
int var1 = this.var2;
int var2 = this.var1;
this
which will look for the assigned variable in the class, not just the context it is followed by.