Geebs
Geebs

Reputation: 125

using "this.field = value" vs "field = value"

I know what this does and why it's useful - this question did a great job of explaining it. However, in the chosen answer they used this to also assign parameters. Does doing

private int aNumber;

public void assignVal(int aNumber){
    this.aNumber = aNumber;
}

have any advantage over this?

private int aNumber;

public void assignVal(int aVal){
    aNumber = aVal;
}

Upvotes: 0

Views: 80

Answers (2)

pczeus
pczeus

Reputation: 7868

There is no performance or other obvious advantage for using this.aNumber vs. just aNumber, other than possibly clarity of to which object instance the aNumber belongs. Basically it comes down to preference.

When using just aNumber, the this prefix is implied.

One possible advantage and a case where using the this becomes necessary is when you have a method that has an argument passed to the method that has the exact same name as a class instance variable. In this case, it is necessary to prefix the class instance variable with this to 'choose' the right property to access.

For example, if you have a class and method declared as:

class ThisExample{
    private int aNumber;

    public void setANumber(int aNumber){
        //Here is is necessary to prefix with 'this' to clarify 
        //access to the class instance property 'aNumber'
        this.aNumber = aNumber; 
    }
}

Upvotes: 1

Natecat
Natecat

Reputation: 2182

It means that you don't have to figure out 2 variable names that refer to one thing. It is slightly more readable, and makes it so your variables are always descriptive of the value.

Upvotes: 0

Related Questions