[PRL] Java and shadowing local variable declarations

Richard Cobbe cobbe at ccs.neu.edu
Mon Jun 5 18:06:10 EDT 2006


On Mon, Jun 05, 2006 at 05:45:50PM -0400, bjchamb at cc.gatech.edu wrote:
> Not sure if this will help, but I found the following online:
> 
> "You may not redefine a local variable inside a block nested within its
> scope. Local variables may hide instance variables however. Any you may
> reuse local variables inside blocks, so long as they don't nest."

Yeah, that's consistent with what I've seen elsewhere on the web and in
my experiments, though it's not complete.  Unfortunately, nobody says it
this succinctly, but I *think* the rule is this:

    A local variable may not shadow another variable binding (whether it
    be another local variable, a method argument, or a catch argument)
    within the same class.  A local variable binding may, however,
    shadow another variable binding in an outer class.

See <http://java.sun.com/j2se/1.3/compatibility.html>.

That is, the following is legal:

    class Outer {

        void m() {
            int x;

            class Inner {
                void m2() {
                    int x;  // shadows the x defined above.
                    doSomethingInteresting();
                }
            }

            // back in m's body
            doSomethingElseInteresting();
        }
    }

> Given that it is illegal, it seems the sentence is almost backward. 

Indeed.  This is one of the reasons why the original sentence is so
confusing.

Thanks,

Richard



More information about the PRL mailing list