Possible Duplicate:
Java - when to use 'this' keywo开发者_如何转开发rd
Is it generally good convention to references class attributes with 'this.' even if it would reference the attribute by default anyway? Or should I only use it when absolutely necessary?
It would make things clearer to the programmer, and to avoid any confusing errors if the programmer added any new variables with the same name.
Some people have a convention for private member variables to prepend or append an underscore. In those cases, it's pretty clear that the this
is implied.
If you don't have a naming convention for private members, then the this
is a good way to indicate that the variable you are reading/writing is a member variable.
I prefer not to have any variables with different scopes (parameters, members, locals) ever sharing the same name. I avoid that with a naming convention for members.
Use it in copy constructors and other instances where you must. Eg:
Foo(Foo rhs) {
this.bar = rhs.bar;
this.baz = rhs.baz;
}
Most modern IDEs will color code your member variables, so you can differentiate them from args. Or you can use a naming scheme that lets you know what the members are, such as prefixing with m_.
Its good practice to never name args the same as your member variables so you don't run into such collisions.
HTH.
精彩评论