Java inner class, local variable plus final analysis

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.