The this keyword is useful when you are trying to access the object that you are invoked in a method . Confused! let’s see .
- Sometimes a method will need to refer the object that invoked it . Here , If you want to invoke a method into existence , then you are using object to invoke that particular method.So if you want to refer the data within the object , then you will use this keyword .
- this can be used inside any method to refer to the current object .
- That is , this is always reference to the object on which the method was invoked .
- You can use this anywhere a reference to an object of the current class type is permitted.
For better understanding actually what this is , consider the following example .
PROGRAM ON ‘this’ KEYWORD :
IN THE ABOVE PROGRAM THE DEFAULT VALUES OF X , Y, AND Z ARE ZERO
MEMORY ALLOCATION :
PROGRAM 2 :
IN THE ABOVE PROGRAM THE DEFAULT VALUE OF X IS 200. If You want the actual value of x then make this statement
System.out.println(” The original value of x is : “+t.x); // it prints the value of actual ‘x’ . That is, the instance variable value.
IMPORTANT POINTS :
- Here , you should remember one thing that , every method will contain ‘this‘ block with respect to the object . That is , when you are invoking a method with respect to some ‘t‘ object , then the method inside the ‘this’ will refer to that particular ‘t‘ object .
- Whenever , an object is created , then the object will automatically filled with the instance variables with their respected values ( default values). This you will be clearly understands by the time of constructors .