Why must the local variables used in Java anonymous internal class methods be defined as final?

Source: Internet
Author: User
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.

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.