【问题标题】:Why was it made possible from JDK 8 that a local inner class (inside a method) can access the non-final local variables of the enclosing method? [duplicate]为什么从 JDK 8 开始,本地内部类(方法内部)可以访问封闭方法的非最终局部变量? [复制]
【发布时间】:2021-03-02 16:08:48
【问题描述】:
class Outer
{
    public void method1()
    {
        int x = 10;
        class Inner
        {
            public void inMethod()
            {
                System.out.println(x);
            }
        }
        Inner i  = new Inner();
        i.inMethod();
    }
    
    public static void main(String[] args)
    {
        Outer obj = new Outer();
        obj.method1();
    } 
}

我在 StackOverflow 上回答了几个问题,即使这些问题都没有准确的答案。 Method local inner class - can access non final local variable

【问题讨论】:

    标签: java methods local inner-classes final


    【解决方案1】:

    嗯,x 没有标记为最终结果,但它是 effectively-final。 如果您在int x = 10; 下方添加x += 5;,它将不再起作用,因为该变量不再是有效的最终变量。 https://www.baeldung.com/java-effectively-final

    我想这主要是为了更好地支持 lambdas 而改变/实现的。想象一下,如果您想在 lambda 中使用变量 final,则必须始终标记它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多