I have a class with a fields called "a". In the class I have a method and in the list of arguments of this method I also have "a". So, which "a" I will see inside of the method? Will it be the field or it will be the argument of the method?
public class myClass {
private String a;
// Method which sets the value of the field "a".
public void setA(String a) {
a = a;
}
}
By the way, there is a similar situation. A method has some local (for method) variables whose names coincide with the names of the fields. What will the "see" the method if I refer to such a method-local variable inside the method (the field or the local variable)?
The more local scope has the priority, so the parameter a
will hide the field a
. In effect, you set the value of parameter a
to itself. The proper idiom to avoid name clashes (and improve readability) is to use this
to explicitly mark the class member:
public void setA(String a) {
this.a = a;
}
The same is true for local variables vs member variables: local variables hide member variables with the same name.
To add to all the answers recommending:
public void setA(String a) {
this.a = a;
}
it's important to realise that omitting the this
will simply set the parameter to itself. By using final
thus
public void setA(final String a) {
this.a = a;
}
you can eliminate errors caused by omitting this
. Using final
is a good practise whenever specifying parameters and fields that aren't intentionally required to change.
The closest one. That is,
a = a;
inside the method has no effect since both refer to the argument a. To refer to the instance variable a you use the this keyword.
this.a = a;
The local version will "shadow" the instance variable by the same name. One pattern to get around this in accessors like your is this:
public void setA(String a) {
this.a = a;
}
which uses the this
keyword to be explicit about scope.
You need to use this
to access the class
variable, otherwise it will always take the parameter variable.