I'm just curious about the use of this
, because the sample code and documentation of Android don't make use of the this
keyword (I like to believe that the android engineers are generally smart, thus my using them as a basis). I'm just curious about the underlying reason that the android engineers don't make use of this
much.
Its mainly a stylistic difference. I've yet to see a argument as to why its good or bad. Personally I like to use it and there are a few instances when you need to use it.
For example if you have a Anonymous Inner class that wants to call a method of the parent class you need this
. Example:
class MyClass{
protected void doSomething(){
}
OnClickListener n = new OnClickListener(){
public void onClick(View v){
MyClass.this.doSomething();
}
};
}
Another reason to use this
is if a method argument masks a member variable. In that case you can use this
to distinguish between the two, although I'd recommend you rename the argument to something that is non masking.
class MyClass{
protected int val;
public void setVal(int val){
this.val = val; // set the member variable equal to the method argument
}
}
Another reason to use this
is when passing a pointer to the current class instance from within that instance. An example of this is when you create a new Intent
Intent i = new Intent(this, NewActivity.class);
There are probably more places where you'll need to use this
. These are the first few that came to mind.
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