This Keyword In Java : Introduction
- This keyword in Java refers to the current calling object.
- In simple terms this 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 :
1) It can be used to refer current class instance variable, which removes ambiguity in naming variables. Let us take an example when this keyword is not used.
- 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.
- 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).
2) 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.
3) 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.
- 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.