In Java, what's the difference between "var = 3;" and "this.var = 3;"?

The sole purpose of this.var is to distinguish from external variable names that may conflict?

+4
source share
4 answers

This usually happens when you shade. Here is an example of shading.

public class YourClass { private int var; } 

It happens that you have this method:

 public void yourMethod(int var) { this.var = var; // Shadowing } 

'this.var' is your instance variable and is declared below your class. Although, on the other hand, in my example, var was a parameter.

+5
source

Using this explicitly indicates the var instance, as opposed to a constructor / method variable or parameter of the same name.

+3
source

One use case:

If your method / constructor parameter is also called var , and you want to access the instance variable in this method, you may need to explicitly tell this.var use the instance variable.

+2
source

Sometimes, when you write a constructor, the names of the variables you pass as arguments may have the same name as the instance variables that you specified in your methods. Thus, this.var refers to the actual instance variable.

+1
source

All Articles