Given the following code:
public class A {
static final long tooth = 1L;
static long tooth(long tooth){
System.out.println(++tooth);
return ++tooth;
}
public static void main(String args[]){
System.out.println(tooth);
final long tooth = 2L;
new A().tooth(tooth);
System.out.println(tooth);
}
}
Can you please explain me the concept of shadowing ?
And another thing, what tooth
is actually used in the code from the main method ?
And i know it's a very ugly code, but ugly is the standard choice for SCJP book writers.
When you are at this point
the class property (
static final long tooth = 1L;
) is used, then a newtooth
is declared, which shadows the class property, meaning that it is used instead of that.Inside the
tooth
method thetooth
variabile is passed as value, it will not be modified, you can see this by executing themain
which gives: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:
}
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.