0

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;
}
Community
  • 1
  • 1
Geebs
  • 125
  • 1
  • 1
  • 9
  • 2
    No, it is strictly and exactly the same. The difference between the two is a matter of opinion. – Tunaki Apr 23 '16 at 20:44
  • i dont see any performance issue on both. – Priyamal Apr 23 '16 at 20:54
  • `this.` is used to instruct the **COMPILER** only (the bytecode generated is the same) about what you want to address, i upvoted this question since i dont see why it should be -1 its a valid question. the advantage of the first method is that you keep the naming of variables consistent. a common practice is to use a slightly different name like `number` and `Number` just to avoid using `this.number`. its a horrible practice (that I admit to sometimes doing :) ). – n00b Apr 23 '16 at 21:18
  • Also I often use `this.` even when it is not needed - it makes the code more readable AND it doesnt create bugs when someone decides to add a parameter that is named the same as a class field. – n00b Apr 23 '16 at 21:20

2 Answers2

1

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; 
    }
}
pczeus
  • 7,709
  • 4
  • 36
  • 51
0

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.

Natecat
  • 2,175
  • 1
  • 17
  • 20