What is variable shadowing used for in a Java class?
The basic purpose of shadowing is to decouple the local code from the surrounding class. If it wasn't available, then consider the following case.
A Class Foo in an API is released. In your code you subclass it, and in your subclass use a variable called bar. Then Foo releases an update and adds a protected variable called Bar to its class.
Now your class won't run because of a conflict you could not anticipate.
However, don't do this on purpose. Only let this happen when you really don't care about what is happening outside the scope.
What are Shadow Variables in Java?
Instead of providing my own description i may ask you to read about it for example here: http://en.wikipedia.org/wiki/Variable_shadowing. Once you understood the shadowing of variables i recommend you proceed reading about overlaying/ shadowed methods and visibility in general to get a full understanding of such terms.
Actually since the question was asked in Terms of Java here is a mini-example:
public class Shadow {
private int myIntVar = 0;
public void shadowTheVar(){
// since it has the same name as above object instance field, it shadows above
// field inside this method
int myIntVar = 5;
// If we simply refer to 'myIntVar' the one of this method is found
// (shadowing a seond one with the same name)
System.out.println(myIntVar);
// If we want to refer to the shadowed myIntVar from this class we need to
// refer to it like this:
System.out.println(this.myIntVar);
}
public static void main(String[] args){
new Shadow().shadowTheVar();
}
}
Variable shadowing in Java
Variables aren't polymorphic. When you access m.name
, that will always use the Mammal.name
field which is part of that object, regardless of the execution-time type of the object. If you need to get access to Zebra.name
, you need an expression with a compile-time type of Zebra
.
The makeNoise
method is called virtually though - the implementation used at execution time does depend on the type of the object.
Note that if you make all your fields private - which is generally a good idea anyway - this doesn't end up being an issue.
This is actually hiding rather than shadowing. See JLS section 8.3 for details on hiding, and section 6.4.1 for shadowing. I can't say that I always keep the differences straight...
Java method overriding and variable shadowing
Method calls are virtual in Java, which means that the method from an object's actual type is called, regardless of what type the reference was which you used to access the object. Direct field access on the other hand is not virtual, so which r
you access will depend on the type of the reference through which you reached it.
Variables shadowing in Kotlin for inner classes: how variables are resolved?
When you do var a = 2
inside the class A
, you're not actually shadowing any variable. You're declaring that a
is a field of class A
, and it defaults to 2.
When you reference a variable in front of a class, Kotlin will add an implicit this
(e.g. a
becomes this.a
) if there is a field with that name but not an upper-level variable with that name. So, the outer a
takes precedence over the field, and you'd have to use this.a
to access the inner a
.
The concept of shadowing
There's nothing magical about shadowing as a concept. It's simply that a reference to a name will always be referencing the instance within the nearest enclosing scope. In your example:
public class A {
static final long tooth#1 = 1L;
static long tooth#2(long tooth#3){
System.out.println(++tooth#3);
return ++tooth#3;
}
public static void main(String args[]){
System.out.println(tooth#1);
final long tooth#4 = 2L;
new A().tooth#2(tooth#4);
System.out.println(tooth#4);
}
}
I've annotated each instance with a number, in the form "tooth#N". Basically any introduction of a name that is already defined somewhere else will eclipse the earlier definition for the rest of that scope.
Related Topics
Why Does Runtime.Exec(String) Work for Some But Not All Commands
How to Sort an Array of Objects in Java
Real World Example of the Strategy Pattern
How to Stop a Java Thread Gracefully
Difference Between Null and Empty ("") Java String
How to Write a Custom JSON Deserializer for Gson
What Is the Garbage Collector in Java
How to Override Class Variables in Java
Which Is the Best Library for Xml Parsing in Java
Jformattedtextfield Is Not Properly Cleared
How to Check If the User Is Pressing a Key
Are Static Fields Open for Garbage Collection
How to Monitor the Computer's Cpu, Memory, and Disk Usage in Java
Collect Successive Pairs from a Stream
Why Should a Java Class Implement Comparable
Jsoup Java HTML Parser:Executing JavaScript Events
How to Switch to the New Browser Window, Which Opens After Click on the Button
Where Are Static Methods and Static Variables Stored in Java