Shading concept

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); } } 

Could you explain the concept of shading to me? And what else is that tooth really used in the code from the main method?

And I know that this is very ugly code, but ugly is the standard choice for authors of SCJP books.

+2
source share
2 answers

There is nothing magical about obscuring as a concept. It is simply that a reference to a name will always refer to an instance within the nearest spanning area. 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 annotated each instance with a number in the form of "tooth # N". In principle, any introduction of a name that is already defined elsewhere will overshadow the previous definition for the rest of this area.

+2
source

When you are at this moment

 System.out.println(tooth); 

the class property is used ( static final long tooth = 1L; ), then a new tooth declared that shades the class property, which means that it is used instead.

Inside the tooth method, the tooth variabile parameter is passed as a value, it will not be changed, you can see this by doing main , which gives:

 1 3 2 
+1
source

All Articles