Java Local Variable Scope: Final or Effectively Final in Inner Classes and Lambdas
In Java, a local variable defined within an enclosing scope (such as a method or a lambda expression) must be declared as final or effectively final if it is accessed by an inner class or lambda expression defined within that scope.\n\nThe reason for this restriction is that, when the inner class or lambda expression is created, it captures and stores a reference to the local variable. If the variable were allowed to change its value after the inner class or lambda expression is created, it would lead to unpredictable behavior and potential bugs.\n\nA variable declared as final cannot be reassigned after its initial value is assigned. On the other hand, an effectively final variable is one that is not explicitly declared as final, but its value does not change after it is assigned for the first time.\n\nHere's an example to illustrate this:\n\njava\npublic void someMethod() {\n int x = 10; // local variable\n \n // Inner class\n class InnerClass {\n public void printX() {\n System.out.println(x); // accessing the local variable\n }\n }\n \n // Lambda expression\n Runnable runnable = () -> {\n System.out.println(x); // accessing the local variable\n };\n \n // Changing the value of x would cause a compilation error\n // x = 20;\n}\n\n\nIn the above example, the local variable x is accessed by both the inner class InnerClass and the lambda expression runnable. If you try to change the value of x after it is assigned, it will cause a compilation error because x is not declared as final or effectively final.\n\nBy enforcing this restriction, Java ensures that the captured local variables remain consistent and avoids potential issues caused by changing the variable's value.
原文地址: https://www.cveoy.top/t/topic/pZGw 著作权归作者所有。请勿转载和采集!