Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: local variable a is accessed from within inner class; needs to be declared final

Tags:

java

class Outer
{
    void m1()
    {
        int a=12;
        class Inner
        {
            void show()
            {
                System.out.println(a);
            }
        }
        new Inner().show();
    }

}

Here when i am compiling this code then i am getting error that is local variable a is accessed from within inner class; needs to be declared final. but here "int a" is a local variable so why we need to declare as final for accessing in inner class .

like image 886
Mahesh kumar Dwivedi Avatar asked Oct 29 '25 15:10

Mahesh kumar Dwivedi


2 Answers

A local variable needs to be declared final if it's used in an inner class. For a local variable to be used in such an inner class, Java behind the scenes takes a copy of the local variable and makes it into an implicit instance variable so the inner class can access it. Because it's a copy, the copy could be wrong if the value changes. So the compiler forces you to make it final.

Note that in Java 8, this would compile, because a is "effectively final" -- not declared final, but never changed once initialized.

Section 8.1.3 of the JLS states:

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

Section 4.12.4 of the JLS states:

A local variable or a method, constructor, lambda, or exception parameter is effectively final if it is not declared final but it never occurs as the left hand operand of an assignment operator (§15.26) or as the operand of a prefix or postfix increment or decrement operator (§15.14, §15.15).

In addition, a local variable whose declaration lacks an initializer is effectively final if all of the following are true:

  • It is not declared final.

  • Whenever it occurs as the left-hand operand of an assignment operator, it is definitely unassigned and not definitely assigned before the assignment; that is, it is definitely unassigned and not definitely assigned after the right-hand operand of the assignment (§16 (Definite Assignment)).

  • It never occurs as the operand of a prefix or postfix increment or decrement operator.

like image 198
rgettman Avatar answered Oct 31 '25 06:10

rgettman


You can easily work around this by declaring your final variable as an array:

final int x[] = {2};

then from within your inner class, set the array value (example with method call returning a value):

x[0] = methodcall();

or (example with just setting the value to 10):

x[0] = 10;
like image 24
Will Buffington Avatar answered Oct 31 '25 05:10

Will Buffington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!