package test.inner_class;public interface MyInterface { public void work(); }
package test.inner_class;public class Test { public static void main(String[] args) {new Test().f("whang"); } private void f(final String username) {new MyInterface() { @Override public void work() {System.err.println(username + " working..."); }}.work(); }}
In the above Code, the username variable of method F in test must be defined as final, otherwise it cannot be used in the work method of the internal class.
In core Java 8th Editon, a local variable that is declared final cannot be modified after it has been initialized. thus, it is guaranteed that the local variable and the copy that is made inside the local class always have the same value.
In fact, we need to define final to prevent unexpected problems caused by the variable's reference being modified when the variable is called.
After compilation, two class files are displayed: Test. Class and test $1. Class. Test $1 is our internal Anonymous class. for decompilation, see these two files:
D:\workSpace\Test\bin\test\inner_class>javap -private TestCompiled from "Test.java"public class test.inner_class.Test extends java.lang.Object{ public test.inner_class.Test(); public static void main(java.lang.String[]); private void f(java.lang.String);}
D:\workSpace\Test\bin\test\inner_class>javap -private Test$1Compiled from "Test.java"class test.inner_class.Test$1 extends java.lang.Object implements test.inner_class.MyInterface{ final test.inner_class.Test this$0; private final java.lang.String val$username; test.inner_class.Test$1(test.inner_class.Test, java.lang.String); public void work();}
In test $1, the local variable username used in method work is used as a private member variable of the internal class and initialized using the constructor.