This is mainly a stylistic difference. I still do not see arguments in favor of why this is good or bad. Personally, I like to use it, and there are some examples when you need to use it.
For example, if you have an Anonymous Inner class that wants to call the 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 for using this
is an argument to a method that masks a member variable. In this case, you can use this
to distinguish between the two, although I would recommend that you rename the argument to something that is not masked.
class MyClass{ protected int val; public void setVal(int val){ this.val = val;
Another reason for using this
is to pass a pointer to the current instance of the class from that instance. An example of this is the creation of a new Intent
Intent i = new Intent(this, NewActivity.class);
There are probably more places where you will need to use this
. These are the first few that come to mind.
source share