- To specifically denote that the instance variable is used instead of a static or local variable. That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absense of the this denotes the local variable. If the local variable that is parameter's name is not same as instance variable, then whether or not this is used. this denotes the instance variable.
-
This is used to refer the constructors
public JavaQuestions(String javaPapers) {
this(javaPapers, true);
}
This invokes the constructor of the same Java class which has two parameters.
- This is used to pass the current java instance as parameter obj.itIsMe(this);
- Similar to above, this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results when used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
- This can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by,
Class className = ABC.class;
and must be understood.
As always, this is associated with its instance and this will not work in static methods.