this keyword holds the link of the current object. Let's take an example to understand it.
class ThisKeywordExample { int a; int b; public static void main(String[] args) { ThisKeywordExample tke=new ThisKeywordExample(); System.out.println(tke.add(10,20)); } int add(int x,int y) { a=x; b=y; return a+b; } }
In the above example, there is a class name ThisKeywordExample, consisting of two data instances a and b. there is an add method that first sets the number to a and b, and then returns the add.
Instance data elements take memory when we create an object of this class and join the refrence variable into which we hold the refrence of this object. In the above example, we created a class object in the main method and held the refrence of this object to the tke refrence variable. when we call the add method, a and b are available in the add method because the add method does not have an object reference. The answer to this question will clear the concept of this keyword.
the above code is treated by the JVM as
class ThisKeywordExample { int a; int b; public static void main(String[] args) { ThisKeywordExample tke=new ThisKeywordExample(); System.out.println(tke.add(10,20,tke)); } int add(int x,int y,ThisKeywordExample this) { this.a=x; this.b=y; return this.a+this.b; } }
the above changes are performed by the JVM, so it automatically passes another parameter (object refrence) to the method and hold it in the refrence variable and get access to the instance element of this object to pass this variable.
The above changes are performed by the JVM, if you compile the code, then there is a compilation error because you do not have to do anything about it. This is handled by the JVM.
Jatin khurana
source share