Before using internal classes, the external local variables to be final is not a special understanding, today's whim want to get a clear.
1 Public classOuter {2 PublicParent Method () {3 Final intn = 8;4 5 classInnerextendsparent{6 Public voidShow () {7System.out.println ("Number:" +n);8 }9 }Ten return NewInner (); One } A Public Static voidMain (string[] args) { -Outer o =NewOuter (); -Parent p =O.method (); the p.show (); - } - } - + classparent{ - Public voidShow () { +System.out.println ("Parent"); A } at}
First, I define an int type variable with the inner (class name) inner class in the method approach. and wrote it in inner.
The show () method refers to the n variable, plus the final decoration. Then I returned to the inner object, paying attention to analyzing this method
After execution, the variable n has been destroyed. So why is the n variable still there? And final will always reside in memory? In
I checked the final life cycle on the internet and found it wasn't. Then find the answer in a technical post.
If you define an anonymous inner class, and you want it to use an object that is set externally, the compiler requires its argument reference
is final. By research, the Java Virtual machine is implemented in such a way that the compiler detects whether there is a direct use of external
When you define a variable, you define a variable of the same type if you have access, and then give yourself an external variable in the constructor method.
Defines the variable assignment value. Reference to http://developer.51cto.com/art/200906/128214.htm
Java inner class, local variable plus final analysis