Geebs Geebs - 7 months ago 5
Java Question

using "this = something2" vs "something1 = something2"

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;
}

Answer

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; 
    }
}
Comments