Should you use "this.variablename" or just "variablename" to reference a member variable in a method?
6 Answers
You can use whichever you want in most cases. If your method parameter or local variable has the same name then you'll need to use this to distinguish the instance variable. Be consistent!
1 Comment
You can do either, it's just a matter of taste, but I've seen a lot of Java code use "this." because the arguments to the method are named the same as the member field a lot of times.
You could argue that using "this." also helps readability, because you immediately know it's a member, but you could also argue that "this." hurts readability, because it's just an extraneous word.
2 Comments
I only use this. in two circumstances:
- To disambiguate between the field and a local of the same name, for example in a setter;
- When my method has a
thatparameter, becausethisandthatmake for nice readable code.