0

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!

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
  • and http://stackoverflow.com/questions/1092099/what-is-variable-shadowing-used-for-in-a-java-class – jmj Sep 12 '14 at 00:02

2 Answers2

0

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64