3

When using Java, is there a way to get a compiler warning (using Eclipse, if it matters) when a child class shadows a super class's instance variables by declaring another one of the same name? For example:

class A {
    String variable;

    A() {
        variable = "A";
    }
}

class B extends A {
    int variable;

    B() {
        variable = 1;
    }
}

B b = new B();
System.out.println("Variable value: " + b.variable + ", " + ((A) b).variable);
// prints out: "Variable value: 1, A"

I'd like to be warned in B that variable already exists.

Steve Haley
  • 55,374
  • 17
  • 77
  • 85
  • 1
    Why? if you make your fields private as you are supposed to, then it doesn't conflict anyway. – Robert Dec 10 '12 at 17:02
  • Just because it can be useful to know, at the prototype stage when I'm not writing full setter/getter methods for everything, as it can create unexpected bugs. – Steve Haley Dec 10 '12 at 17:12
  • 1
    It's called shadowing, not overriding and yes there are options to warn against it. – Robin Dec 10 '12 at 17:17
  • @Robin Ah, yes "shadowing". I knew 'override' wasn't the right word, but the right one slipped my mind. – Steve Haley Dec 10 '12 at 17:21

1 Answers1

6

Yes. In Eclipse go to

Preferences->Java->Compiler->Errors/Warnings

In that pane there is a subsection on Name shadowing and conflicts that contains the options you are looking for.

Robin
  • 24,062
  • 5
  • 49
  • 58
  • +1, i just tried it and it worked for me .. :P, but would it be considered overriding of variables ?? i think its considered more of shadowing than overriding, am i right ? – PermGenError Dec 10 '12 at 17:19