Talk:Variable shadowing

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia

Local variable shadowing vs. member variable shadowing[edit]

All examples show cases of variable shadowing except that of Java in my opinion.

In the example with Java, it's just a class field shadowed by a local variable.

It's my opinion because I can't find a precise definition of "variable shadowing": Is it just "any redefined variable name will take precedence" (and may lead to confusion) or "any redefined variable name will make the shadowed variable hidden/unreachable" (which is more confusing)?

In my opinion, the current Java example is not a case of "variable shadowing" since the shadowed field is still accessible (with the syntax this.myIntVar), while in all the other examples the shadowed variables are not accessible anymore/at all.


I don't know if my definition hardens the real one (which I can't find). I think the example in Java should be modified, for an example (of "real" variable shadowing IMO) like:

public class Shadow {

	public static void main(final String[] args) {
		final int myIntVar = 1;
		final int anotherName = 2;
		new Runnable() {
			
			@Override
			public void run() {
				System.out.println(myIntVar); // prints 1
				final int myIntVar = 5;
				System.out.println(anotherName); // prints 2
				System.out.println(myIntVar); // prints 5, we can't see anymore the outer variable myIntVar
			}
		}.run();
		System.out.println(myIntVar); // prints 1
	}
}