为什么匿名内部类引用外部局部变量不用加 final 也不报错

Java 面试 About 759 words

Java 代码

匿名内部类引用了局部变量,编写代码时没有用final修饰也没有报错,因为编译器会检查后续有没有写操作,如果有,则在编译器时就会报错(包括匿名内部类方法体内也不能进行写操作)。如果只有读操作,编译器会帮忙加上final关键字。

public class Test {

    public static void main(String[] args) {
        int x = 10;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // x = 30;
                System.out.println(x);
            }
        };
        // x = 20;
        System.out.println(x);
    }

}

反编译 class

可以看到:反编译后编译器帮忙加了final关键字。

public class Test {
    public Test() {
    }

    public static void main(String[] args) {
        final int x = 10;
        Runnable var10000 = new Runnable() {
            public void run() {
                System.out.println(x);
            }
        };
    }
}
Views: 1,272 · Posted: 2022-05-16

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh