This Keyword In JAVA | Core Java Tutorial | Minigranth
This Keyword In Java : Introduction
Thiskeyword in Java refers to the current calling object.
In simple termsthis is a keyword in Java which is a reference to the object that was used to invoke a method.
This keyword can be used in many contexts. We will be discussing about three of them, which are:
It can be used to refer current class instance variable, which removes ambiguity in naming variables. Let us take an example when thiskeyword is not used.
Output
We can clearly see in the output that if we don’t use this keyoword then there occurs naming conflict. Compiler cannot differentiate between data members and formal parameters which are of same name.
Hence even on passing values through parameterized constructor the output is null and 0.Let us rectify this using this keyword.
Output
Now the passed values are reflected in the output. Hence using this keyword we can tell compiler that we have to assign the values of formal parameters(name,age) to the instance variables (this.name and this.age).
This keyword can be used to call current class method. If you do not provide this keyword then it is added implicitly by compiler upon invoking the method. Let us understand with an example.
Output
This keyword can be used to invoke current class constructor.
This keyword can be used to call current class constructor. This means we can use this() within parameterized constructor to call default constructor or vice versa.
Note :Constructor call using this must be the first statement in the block.
Example
Output
In the above example we have called parameterized constructor using this keyword from within default constructor. Vice versa also possible.
Also this() statement is first statement in the block.