jdk1.8之后内部类调用局部方法不用final

我们都知道java的内部类
局部内部类如果要去访问局部变量,那么局部变量必须声明为final类型。
具体可以看下java内部类介绍
也就是

public class demo {
    public static void main(String[] args) {
        doSomething();
    }

    private static void doSomething() {
        final String str1 = "Hello";
         String str2 = "World!";
        // 创建一个方法里的局部内部类
         class Test {
            public void out() {
                System.out.println(str1);
                 System.out.println(str2);
            }
        }
        Test test = new Test();
        test.out();

    }
}

这个方法在运行到 System.out.println(str2); 时候会报错
由于str2没有声明为final,编译抛出异常:Cannot refer to the non-final local variable str2 defined in an enclosing scope

但是现在运行的时候却发现成功了
在这里插入图片描述
感到十分的奇怪 于是查了下资料
得知 JDK1.8之后匿名内部类访问方法中的局部变量不用加final修饰

具体可以文档参考https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html#accessing-members-of-an-enclosing-class

发布了29 篇原创文章 · 获赞 19 · 访问量 6508

猜你喜欢

转载自blog.csdn.net/wenzhouxiaomayi77/article/details/97941135