Normally, I use this
in constructors only.
I understand that it is used to identify the parameter variable (by using this.something
), if i
Instance variables are common to every object that you creating. say, there is two instance variables
class ExpThisKeyWord{
int x;
int y;
public void setMyInstanceValues(int a, int b) {
x= a;
y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
}
class Demo{
public static void main(String[] args){
ExpThisKeyWord obj1 = new ExpThisKeyWord();
ExpThisKeyWord obj2 = new ExpThisKeyWord();
ExpThisKeyWord obj3 = new ExpThisKeyWord();
obj1.setMyInstanceValues(1, 2);
obj2.setMyInstanceValues(11, 22);
obj3.setMyInstanceValues(111, 222);
}
}
if you noticed above code, we have initiated three objects and three objects are calling SetMyInstanceValues method. How do you think JVM correctly assign the values for every object? there is the trick, JVM will not see this code how it is showed above. instead of that, it will see like below code;
public void setMyInstanceValues(int a, int b) {
this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
this.y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}