The concept of shadowing

前端 未结 2 1894
走了就别回头了
走了就别回头了 2020-12-20 00:53

Given the following code:

public class A {
 static final long tooth = 1L;

 static long tooth(long tooth){
  System.out.println(++tooth);
  return ++tooth;
          


        
2条回答
  •  孤城傲影
    2020-12-20 01:21

    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.

提交回复
热议问题