Java Coding Style – Accepted Style for Using the `this` Keyword

coding-stylejava

I come from languages like Python or Javascript (and others that are less object-oriented) and I am trying to improve my working knowledge of Java, which I know only in a superficial way.

Is it considered a bad practice to always prepend this to the current instance attributes? It feels more natural to me to write

...
private String foo;

public void printFoo() {
    System.out.println(this.foo);
}
...

than

...
private String foo;

public void printFoo() {
    System.out.println(foo);
}
...

as it helps me to distinguish instance attributes from local variables.

Of course in a language like Javascript it makes more sense to always use this, since one can have more function nesting, hence local variables coming from larger scopes. In Java, as far as I understand, no nesting like this is possible (except for inner classes), so probably it is not a big issue.

In any case, I would prefer to use this. Would it feel weird and not idiomatic?

Best Answer

In most IDEs, you can simply mouseover the variable if you want to know. In addition, really, if you're working in an instance method, you should really know all the variables involved. If you have too many, or their names clash, then you need to refactor.

It's really quite redundant.