Reputation: 404
I just recently started learning Java. I have a question which is more about conventions used in Java...
So suppose I have class A:
public class A {
public void methodA{
methodB();
}
private void methodB{
}
}
Sometimes I see some people calling private methods inside the class using this (e.g. this.methodB(); ) even if there is no ambiguity. Is it convention to explicitly show people that they are invoking private method or is it just someone's 'style'.
Upvotes: 1
Views: 336
Reputation: 7257
Slightly off-topic in that we're not addressing a private method, rather a private class variable, but it's worth mentioning that sometimes this
is necessary to prevent ambiguity:
public class Example {
private RowMapper rowMapper;
public void setRowMapper(RowMapper rowMapper) {
this.rowMapper = rowMapper;
}
}
On the whole, where there is no ambiguity then this
is redundant syntax.
Upvotes: 0
Reputation: 16311
That's just style. Personally, I somehow like being overly explicit when accessing members, but I can also understand that people find it ugly, particularly if you're using methods or properties of the outer class from an inner class:
public class Outer {
private SomeType member;
private class Inner {
public void innerMethod() {
Outer.this.member.someFunction();
}
}
}
It may help in rare cases where you introduce a name shadowing problem later without noticing - all of a sudden you're calling the wrong function or accessing the wrong variable. Still, qualifying with this
is verbose, and it's not a general rule.
Upvotes: 1
Reputation: 16796
In and of itself, using this
does not clarify much. It can point to:
this
, whatever its visibility.this
's class. (there is usually a warning in that case, but it is only a warning).What it does prevent is:
I'll emphasize that it does not guarantee at all that the method called is private.
It is the first time I hear of this rule - I suspect that, at most, it is a (not that helpful) style rule of a company.
Upvotes: 2