Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

java - The concept of shadowing

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...