Is the only purpose of this.var to distinguish from outside variable names that might conflict?
Usually, this chances occurs when you are shadowing. Here's an example of shadowing.
public class YourClass
{
private int var;
}
It happens that you have this method:
public void yourMethod(int var)
{
this.var = var; // Shadowing
}
'this.var' happens to be your instance variable and is declared below your class. While on the other hand, in my example, var was a parameter.
Using this
explicitly indicates the instance var
as opposed to a constructor/method variable or parameter of the same name.
One use case is:
If your method/constructor parameter also named as var
and you want to access instance variable in that method, then you may need to explicitly tell this.var
to use instance variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With