As far as I know this is used in following situations:
this
keyword is used when we want to refer to instance variable having same name as local variable.But I have gone through my project code where they are using this in getters like:
class a {
int time;
int getValue() {
return this.time * 5.;
}
}
As far as I know, every object has its own copy of instance variables and methods, so will returning this way makes any sense. Please clarify.
Stackoverfow problem referred:When should I use "this" in a class?
Many people (I'm one of them) use this
keywords even when it is not explicitely needed.
this
in front of anything which belong in the same class, the same logic apply to super
.this
by reflex for a better auto-completion (pop-up appear automatically, lazy programmer) in some IDE.These points are mostly opinion based and doesn't really matter.
For the other uses, as you mentionned, it can be used to pass parameter to another constructor, pass the class instance or to distinct when you have two variables with the same name.
However, IMO, it is way simplier to just not have multiple variables with the same name.
When you have a method like the following one:
public void setFoo(Foo foo) {
this.foo = foo;
}
Using this
is mandatory. Otherwise, it would assign the argument foo to itself, instead of assigning it to the instance variable.
But that doesn't mean that's the only situation you may use this
. The following code is strictly equivalent:
public void setFoo(Foo newFoo) {
this.foo = newFoo;
}
Although in that case, you might very well write
public void setFoo(Foo newFoo) {
foo = newFoo;
}
because this
is not necessary anymore. That doesn't make it illegal.
So,
int getValue() {
return time * 5;
}
and
int getValue() {
return this.time * 5;
}
are strictly equivalent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With