Adalcar Adalcar - 2 months ago 6
Java Question

what is the difference between foo and in an object (without ambiguosity)

Supposing I have in my code something like that

class c {
private int foo;

public c(int foo)
{ = foo;
public c()
foo = 10; = 10;

In the first constructor, the necessity for
is obvious, but which is the correct one for the second case?

Is it just a matter of coding style?

It might be a duplicate since this is such an elementary question but I have not found the original question


The other explain why foo and are the same; so lets focus on the style aspect. And what matters here is ultimately - your development environment.

When you are using a modern IDE like eclipse or IntelliJ, then the IDE knows exactly what you are doing. It can tell you what is a field; and what is a local variable.

It can even warn you when you have a typo in the parameter declaration, like here:

class Bar {
  private int foo1ed;

  void bar(int fooled) {
    this.foo1 = foo1ed;

[ unfortunately, the java world likes the pattern of shadowing fields with method parameter names; but as shown above, that can go pretty wrong. And some years back, that might have caused ugly ugly bugs ]

In other words: 10, 15 years ago, it would make a significant difference if you wrote "this.field" vs "field"; because back then, the "IDEs" might have done code completion only when you used "this.field". So people used "this." all over the place (I know that because I was one of those folks).

But in 2016; your IDE knows all that; and you get that information instantly. Thus: there is simply no more need to write down "this." any more (except for those constructor calls where you want to assign = foo).

Meaning: years ago, there was real value in writing down "this.". Nowadays, I don't see that value any more. I mainly see "cost" (in terms of "line noise") - additional characters your brain has to digest; that carry no value whatsoever for you.

Finally: I gave some arguments in favor of using "this." only in places where it is really required. But as said; this is about style.

And all style questions are a team question. Meaning: you sit down with the people that work with you; and then the whole team defines the style that everybody should adhere to when working on your project. And then everybody lives up to that.