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.

The 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.

A 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.

Here's an example to illustrate this:

public void someMethod() {
    int x = 10; // local variable
    
    // Inner class
    class InnerClass {
        public void printX() {
            System.out.println(x); // accessing the local variable
        }
    }
    
    // Lambda expression
    Runnable runnable = () -> {
        System.out.println(x); // accessing the local variable
    };
    
    // Changing the value of x would cause a compilation error
    // x = 20;
}

In 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.

By enforcing this restriction, Java ensures that the captured local variables remain consistent and avoids potential issues caused by changing the variable's value

Local variable i defined in an enclosing scope must be final or effectively final

原文地址: http://www.cveoy.top/t/topic/ihrj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录