Lu Xiaoming
Lu Xiaoming

Reputation: 3

Why i can access outer non final variable from a local method inner class

When my friend runs this code. It reports a compile error says it315 has to be final which it is same as the books says. However when i run it in my eclipse it has no problem at all. I can access it315 even though it is not final. I just wonder why.

public class InOut {

    String str=new String("between");

    public void amethod(final int iArgs){

        int it315= 10;
        class Bicycle{
            public void sayHello(){
                System.out.println(str);
                System.err.println(iArgs);
                System.out.println(it315);
            }


        }
        Bicycle  cBicycle=new Bicycle();
        cBicycle.sayHello();

    }

    public static void main(String[] args) {
        new InOut ().amethod(999);

    }

}

Upvotes: 0

Views: 36

Answers (2)

Muneeb Nasir
Muneeb Nasir

Reputation: 2504

reason is, to avoid value change of that variable, while inner class is accessing that variable. compiler copy the values of variable to inner class variables that's why.

as for as why your friend got error concerns, i guess, @Tagir answer is logical,

Upvotes: 0

Tagir Valeev
Tagir Valeev

Reputation: 100309

In Java 8 you can access "effectively final" variables (which are not declared final, but actually not modified). Seems that your friend is using Java 7 (or older) compiler while your Eclipse installation is configured to use Java 8.

Upvotes: 2

Related Questions