The following code runs for both var = putVar; & this.var = putVar;
I understand: "this" is used to identify that - "put this value for just 'my' object". When both work, why do people usually use "this" in setters?
code:
public class PlayingWithObjects
{
public static void main(String[] args)
{
SomeClass classObj = new SomeClass(10);
System.out.println("classObj.getVar: " + classObj.getVar() );
classObj.setVar(20);
System.out.println("classObj.getVar: " + classObj.getVar() );
classObj = new SomeClass(30);
System.out.println("classObj.getVar: " + classObj.getVar() );
}
}
class SomeClass
{
private int var;
public SomeClass(int putVar)
{
var = putVar;
}
public int getVar()
{
return var;
}
public void setVar(int putVar)
{
// var = putVar; // also works
this.var = putVar;
}
}
Am I understanding "this" correctly? Where is "this" used & cannot be replaced. Please post some code.
You can use
this
if you're using the same method argument identifier as a field, but it can be avoided if you simply do not use the same name.Not using the same name is a more common practice to avoid confusion and shadowing. Hence, any reference to
this
in a setter can be replaced with a better naming standard:inParameter
, for instance.The other use of
this
would be to explicitly invoke a constructor. This is a form which can't be replaced with a simpler naming convention:There may also be a case in which you want to return the instance you're working with. This is also something that
this
allows you to do:Because people like to use the same variable name for both the method parameter and the instance variable - in which case you need
this
to differentiate.Like ktm mentioned, setters tend to use the same name as the field for the parameter. In this case, the parameter shadows the field name, so
would just set the parameter to itself rather than setting the field to the parameter.
There are 2 cases I know of, aside from the case ktm mentioned (which I think is obvious and you already knew):
Just to make it very clear that they're referring to the member of the current object.
If you're in an anonymous inner class within another object (ex: of class ClassName), you can use ClassName.this to get the instance of the enclosing object. The reason for this (no pun intended) is that, inside the inner class, this will refer to the inner class.
If a class has an instance variable with some name (say
myVar
), and a method has a LOCAL variable with the exact same name (myVar
), then any reference to the variable will refer to the LOCAL variable. In cases such as these, if we want to specify the class's instance variable, we need to saythis.myVar
. As stated before, this is particularly useful when we want to have setters in which the parameter name is the same as the instance variable that it sets: