views:

47

answers:

5

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)?

+5  A: 

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.

Péter Török
And when working with inner-classes you can use `myClass.this.a` to refer to the `myClass` instance.
Pindatjuh
+1  A: 

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;
Vincent Ramdhanie
Cool! I did not think about the usage of `this`. I though that I need to rename the argument of the method. But now I think that `this` provide a more elegant solution. Thank you.
Roman
+1  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.

quixoto
A: 

You need to use this to access the class variable, otherwise it will always take the parameter variable.

fastcodejava
+2  A: 

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.

Brian Agnew
+1 for recommending additional thing instead of writing almost duplicate answer like others
Yatendra Goel