The this keyword in Java refers to the current object's instance.
It is used to distinguish a local member (e.g. instance variable) from a method parameter with the same name.
By prefixing this to a member (instance variable or method), it can be accessed within the class.
table of content:
- what is this keyword?
- why this keyword is used?
- how to use this keyword?
- conclusion about this keyword
what is "this" keyword?
this is a predefined keyword in java.
Why "this" keyword is used?
this keyword is used for accessing the global/instance member of the class within same class.
How to use "this" keyword?
this keyword always used .(dot) like this.variableName of class.
Example:
class Company{
String name;
public void setName(String name) {
this.name = name;
}
}
Code Briefing
Here, the method setName takes an argument name, which would have the same name as the instance variable name. By using this.name, we are able to distinguish the local member from the parameter name.
Conclusion
This in Java refers to the current object's instance and is used to differentiate local members from
method parameters with the same name, allowing access to members within the class.