Reputation: 13
Assume that there is a class like the following.
public Class SomeClass {
private A getA() {
...
}
public void show() {
A a = getA(); // CASE #1
...
}
public void show2() {
A a = this.getA(); // CASE #2
...
}
Their result are same, isn't? My idiot co-worker insisted that's right!!(it means they're different.)
Upvotes: 1
Views: 820
Reputation: 28588
Here's a case where you may want to use 'this' just to be clear.
class Outer {
A a;
public A getA() {
return a;
}
class InnerSuper {
A a;
public A getA() {
return a;
}
}
class Inner extends InnerSuper {
public void test() {
A a = Outer.this.getA();
A a = this.getA();
}
}
}
Upvotes: 1
Reputation: 1754
I will cite the best example of this pointer I came across in my school days.
class ThisChk
{
int param1;
public int check(int param1)
{
this.param1 = param1; //this.param1 is the class variable param1, param1 is the function parameter with a local scope
return 0;
}
}
Upvotes: 2
Reputation: 72324
They're the same in this context. I'd advocate not using this
since it's implied and it's just cluttering up the code by being there, but it makes no practical difference whether it's there or not.
It's not useless though. The this
keyword is required sometimes, for instance:
<String, String>stringMethod()
, it has to be this.<String, String>stringMethod()
.That's by no means an exhaustive list, just serves as an example to demonstrate while it doesn't make a difference in this case, it can do in other cases!
Upvotes: 6
Reputation: 724102
Your co-worker isn't that much of an idiot after all, because they are the same. In the first case, Java implicitly implies this
.
Upvotes: 3