Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use `this` in Java? [closed]

Tags:

java

this

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.

like image 466
cesar Avatar asked Jan 19 '23 11:01

cesar


1 Answers

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.

like image 176
slayton Avatar answered Jan 25 '23 19:01

slayton