Something I've always wondered; in a class where you can reference a member by either using 'this.[NAME]' or simply [NAME], which is preferred?
For example in Java:
public class foo {
public int bars = 0;
private void incrementBars(){
bars++;
}
}
and
public class foo {
public int bars = 0;
private void incrementBars(){
this.bars++;
}
}
'seem' to have the same effect.
In cases where I instantiate multiple instances of class foo, I'd, so far, do something like:
for (foo f : listOfFoos){
f.incrementBars();
}
and it seems to still work.
Is it technically ambiguous, and if so is there a preferred way?
'this' means 'current object'. In static methods there is no current object. In your example, try replacing this with new Main() .
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .
Definition and Usage The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
We use this, that, these and those to point to people and things. This and that are singular. These and those are plural. We use them as determiners and pronouns.
use this
in the case of variable shadowing
.
class MyClass{
int i;//1
public void myMethod(){
i = 10;//referring to 1
}
public void myMethod(int i){//2
i = 10;//referring to 2
this.i = 10 //refering to 1
}
}
also sometime this
will make code more readable due to our English mindset
There's no ambiguity. If there were, you'd have to use this
.
Some people recommend this
for clarity. Others recommend against it when it's not required, as it introduces "noise". Some modern IDEs or editors may be able to use syntax highlighting to color (for instance) arguments differently from fields for clarity.
Personally I avoid this
when I can and use @unholysampler's underscore convention. Agree on something with your coworkers and put it in your coding standards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With