In Java, the this
keyword represents the current instantiation of the class. So when you create an object:
x obj = new x();
x
has two "instance" (not local) variables y
and z
.
If your class also has methods that contain local variables of the same name, then how can the Java Runtime environment (the computer) know which y
and z
you are referring to? For example:
x(int y, int z){
y = y; //Both z are just the local variables
//of this method and don't change the class.
z = z; //Both z are just the local variables and dont affect class object
}
But if you do the following, then you change the objects y value but not its z value:
x(int y, int z){
this.y = 50; //call this function sets the objects y value to 50
z = z; //But nothing happens to the objects z value because the
//Java Runtime enviornment sees the z and finds its nearest
//scope which is the method its defined in and thus the local
//variable gets set to itself and then deleted after the method
//is called and the object's z value is not changed.
}