This question already has an answer here:
- When should I use “this” in a class? 17 answers
What is the best practise for using the this
keyword in Java? For example, I have the following class:
class Foo {
Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
}
That's fine and all, but Java is clever enough to know what is happening if I change the statement in the constructor to
bar = bar;
So why use the this
keyword? (I realise in some situations, it's totally necessary to use it, I'm just asking for situations like this). Actually, I tend to use the keyword purely for readability sake but what's the common practise? Using it all over the shop makes my code look a bit messy, for example
boolean baz;
int someIndex = 5;
this.baz = this.bar.getSomeNumber() == this.someBarArray[this.someIndex].getSomeNumber();
Obviously a poor bit of code but it illustrates my example. Is it just down to personal preference in these cases?
Depending on convention, you can use it for readability. It stresses the fact that it's an object variable.
I also like to have setter arguments with the same name as the variable (looks better in method signature). You need
this
in this case.It is common to use this keyword in explicit constructor invocation. You can see an example from the documentation.
this
keyword refers to the Object of class on which some method is invoked.For example:
Here in
Abc()
we are callingXyz()
which needs Object of Abc Class.. So we can passthis
instead of newAbc()
, because if we pass newAbc()
here it will call itself again and again.Also we use this to differentiate variables of class and local variables of method. e.g
Here
this.a
is refers to variable a of class Abc. Hence having same effect as you use newAbc().a;
.So you can say
this
refers to object of current class.Actually
will raise this warning
So what you think is wrong, the local scope overrides the class attribute so you MUST use
this
keyword explictly to assign the variable to the class attribute.Otherwise the variable accounted into assignment is just the one passed as a parameter and the class one is ignored. That's why
this
is useful, it's not a fact of readability, it's a fact of explicitly deciding whichbaz
are you talking about.I would say
Personal preference, but I use it to solve ambiguities only, and I suppose in the very rare case to make it obvious that the assigned variable is a field. There are some projects where people use "this.field" on every single field reference. I find this practice visually distracting to the point of being obnoxious, but you should be prepared to see such code once in a while.
I secretly think there's a special place in hell for people who write 500 line classes that have 275 'this' keywords in them, but this style is found in some open source projects, so to each his own I guess.
Use it for Cloning objects (by passing reference of itself through a copy constructor).
Useful for object that inherits
Cloneable
.