Understanding of internal class reference external variables

 

Observation code below

  1, if the comments of the fifth row to open the compiler does not pass, because the variables in the method needs to be final variable or de facto final variable ( Effectively final ) before they can be passed using anonymous inner classes

  2, after the fifth row together with comments, can be translated through a java8, at this time the variable d is the fact that the final variable, the JVM can safely copied to the internal variable in the class

  3. Why do I need to copy to d inner class? Test1 method because the life cycle is shorter than inner classes, resulting in test1 after executing the variables in the stack with the method of destruction and the destruction of the stack, at this time there is an internal class

  4, the second and third methods, internal class also references the external variables, but c and w are allocated to the heap, is not limited life cycle, it is not necessary to copy the inside inner class

 1 public class InnerClassTest {
 2 
 3     void test1() {
 4         int d = 2;
 5         //d = 3;
 6         new Runnable() {
 7             @Override
 8             public void run() {
 9                 System.out.println(d);
10             }
11         };
12     }
13     
14     int c = 1;
15     void test2() {
16         c = 2;
17         new Runnable() {
18             @Override
19             public void run() {
20                 System.out.println(c);
21             }
22         };
23     }
24     
25     void test3() {
26         W w = new W();
27         Thread thread = new Thread(new Runnable() {
28             @Override
29             public void run() {
30                 w.i = 4;
31                 System.out.println(w.i);
32             }
33         });
34         thread.run();
35         System.out.println(w.i);
36     }
37 }
38 class W {
39     int i = 2;
40 }

 

Guess you like

Origin www.cnblogs.com/liangwenhan/p/11318659.html