Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Is the only purpose of this.var to distinguish from outside variable names that might conflict?

like image 218
talloaktrees Avatar asked Dec 06 '12 03:12

talloaktrees


3 Answers

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.

like image 87
Michael 'Maik' Ardan Avatar answered Nov 17 '22 14:11

Michael 'Maik' Ardan


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

like image 3
Lawrence Dol Avatar answered Nov 17 '22 14:11

Lawrence Dol


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.

like image 2
kosa Avatar answered Nov 17 '22 16:11

kosa