views:

47

answers:

3

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'.

+2  A: 

In and of itself, using this does not clarify much. It can point to:

  • An instance field (or method) or an inner class of this, whatever its visibility.
  • A static field or method or a nested class, of one of the classes inherited by this's class. (there is usually a warning in that case, but it is only a warning).

What it does prevent is:

  • static imports
  • local variables
  • class imports (if you have a nested class with the same name as an imported class)

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.

jhominal
+1  A: 

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.

Henning
A: 

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.

Gary Rowe