The this keyword can be very confusing for beginners because we don’t know what is the this keyword referring to. In this topic we’ll dicuss the use of this keyword in Java.
The uses of this keyword
It can be use to refer to the current instance class variables
In the first line of the code above, the this keyword in the this.name refers to the instance variable and not the name argument.
In the second line, it is not gonna work because you are passing the name parameter to itself.
It can be used to call current class constructor.
We can do this by using this()
NOTE: The Call to this() must be the first statement in constructor. Meaning if you call another this() with different signature the compiler won't allow you.
See the constructor with no argument? We call the this keyword and then pass a string argument. The compiler then will find a constructor that matches the signature and then call that constructor.
It can be pass as an argument to a method
Take a look at the code carefully, read it, and try it on your IDE. This is the only way you could understand what is happening here. Like I said, the this keyword can be confusing sometimes.
It can be use to return class instance state
Take your time and read the code carefully cause it is a bit confusing.
The first this on the default constructor
is referring to the constructor that matches its signature(the second constructor).
The second this keyword
is referring to the current object(the current instance class)
Hopefully you understand even just a bit about how the this keyword works. I know it is confusing so just take your time. Try it on your IDE. Run it and mess with it. Thats the best way to understand this this keyword. HA! See what I did there? this "this".