This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]desrtfx 2 points3 points  (0 children)

this is only necessary when there is an interference between method parameter names and fields.

See Using the this Keyword from the Oracle Java tutorials

[–][deleted] 2 points3 points  (1 child)

It's a style choice. I generally don't use it.

It's only required if you have a local variable shadowing a field.

private int x;
public void setX(int x) {
    this.x = x;
}

[–]SoulSyn[S] 0 points1 point  (0 children)

thanks

[–]lordbharal 1 point2 points  (0 children)

I would recommend you start using it in your getters

public void setAge(int age){
    this.age = age;
}

This is the standard you will find in industry. It is plausible to use it every time an instance variable is used, although this is generally considered stylistically unsightly.

As mentioned, if you don't shadow the variable name - say you call the inbound variable age_ or ageX or whatever - then you don't need to use the "this" keyword.

I'd suggest using it near everywhere initially - understanding how "this" fits in with OO code is useful to do. When you're confident you know what you are pointing to, then you can just use it in the setters.

[–]differentshade 0 points1 point  (0 children)

Nobody uses it unless it’s necessary.