1

I find myself frequently making the following error.

public class Foo{

  Bar bar;

  public void doSomething(){
    Bar bar = makeNewBar();
    // bla bla
  }

}

where the error is that I want to set Foo's bar, not a local Bar. I.e, I should say bar = makeNewBar(), not Bar bar = makeNewBar(). Is there a compiler warning flag or something that can detect "namespace collisions" like this? If not, what's a good way to avoid this (short of not making the error, which is obviously the best option =p)?

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
andyInCambridge
  • 1,215
  • 2
  • 13
  • 27
  • 2
    I don't know if there is a compiler warning, but any decent IDE should show you the fact that the local variable hides the instance variable... – assylias Feb 11 '13 at 16:38
  • Use an IDE; they tell you these things. – Brian Roach Feb 11 '13 at 16:39
  • 2
    [Checkstyle can detect this.](http://checkstyle.sourceforge.net/config_coding.html#HiddenField) – millimoose Feb 11 '13 at 16:39
  • 1
    Looks like Eclipse has a setting for this: http://stackoverflow.com/questions/4122959/usage-of-eclipse-warning-field-declaration-hides-another-field-or-variable – EJK Feb 11 '13 at 16:40

2 Answers2

5

That's not really the job of the compiler but most IDE warn you with correct settings if you shadow a variable.

Using Eclipse, go to Preferences / Java / Compiler / Error/Warnings and look for Name shadowing and conflicts.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    In Netbeans it's a hint called "Local Variable Hides a Field": Tools > Options > Editor > Hints > General > "Local Variable Hides a Field" – assylias Feb 11 '13 at 16:42
2

Couldn't you use

this.bar = makeNewBar();

(That will be less confusing to the reader of the class also..)


(OR)

This URL shows that Eclipse can be configured to warn about declarations that hide class members:

http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fpreferences%2Fjava%2Fcompiler%2Fref-preferences-errors-warnings.htm

See the section on "Field declaration hides another field or variable"

The documentation states that this warning is defaulted (in ECLIPSE) to IGNORE, so you are right in that it would have to be explicitly set.

A B
  • 4,068
  • 1
  • 20
  • 23