Final is used for internal class access to local variables, and final uses local variables.
Final is used for internal class access to local variables
public void mRun( final String name){ new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(name); } }.run(); }
When an internal class accesses a local variable, the final modifier must be added before the local variable. Otherwise, the compiler reports an error. We usually do the same. The question is, why should we add the final modifier? I believe that most of my friends have never considered this problem, but when using it, they can simply add it and never go into the principle. This is not desirable for a good programmer. We need to know not only what it is, but also what it is. Now let's analyze why we need to add the final keyword. First, the life cycle of internal classes is Member-level, and the life cycle of local variables is actually a method body. That is to say, when the mRun method is executed and the new thread runs, the new thread will sleep for one second. The main thread continues to execute, the mRun execution is complete, and the name attribute lifecycle ends. 1 second later, Syetem. out. printh (name) is executed. However, the name is no longer in the memory. To prevent such errors, Java strictly requires the azimuth local variables in the internal class and must be modified using the final keyword. After a local variable is modified by final, a local replica is saved in the memory. When an internal class is accessed, the replica is actually accessed. This is like increasing the lifecycle of a local variable. After all, the Java engineer filled this hole for us in advance. Otherwise, I don't know how many friends will worry about internal class local variables.