I'm currently reading about the this
keyword and don't understand why is it useful to do things like:
this.object = object;
(object
is a random variable. I just don't understand why we do like, this.xxx = xxx
)
Help me please!
I'm currently reading about the this
keyword and don't understand why is it useful to do things like:
this.object = object;
(object
is a random variable. I just don't understand why we do like, this.xxx = xxx
)
Help me please!
It's necessary to specify that you want to assign the value to the field, rather than the parameter or local variable:
public void setFoo(Foo foo) {
this.foo = foo;
^ ^
| \--- Take the value of the parameter
\---- Assign to the field
}
If you just wrote:
foo = foo;
in the above, then it wouldn't do anything - it would be assigning the value of the parameter back to the parameter.
Another option, however, is to use a different parameter name instead:
public void setFoo(Foo newFoo) {
foo = newFoo;
}
Now the field and the parameter have different names, so you don't need to find another way to differentiate between them.
imagine having a setter like
private Object obj;
public void setObject (Object obj)
{
this.obj = obj;
}
this this
scope the object to the class field otherwise with
obj = obj;
you would be setting the same object to be the same object.