This is covered by any tutorial on the basics of writing class code in Java, including the official ones, so it's worth reading up on class syntax and the this
keyword from reputable sources.
Within an instance method or a constructor, this
is a explicit reference to the current object. If you omit it, any member reference is still checked against the current object first. As such, this works:
class Dog {
String name;
public Dog(String n) { name = n; }
}
because name
is a member of the current object. Whether you use this.name
or name
makes no difference here.
However, something like this will not do anything useful:
class Dog {
String name;
public Dog(String name){ name = name; }
}
All this does is take the passed in value, and copy that value onto itself, which is then immediately thrown away when the constructor finishes.
In this case, you need to use this
to do anything meaningful:
class Dog {
String name;
public Dog(String name){ this.name = name; }
}
Now the value of name
will explicitly get copied into a variable with the same name that exists as owned by current object.