David
David

Reputation: 81

Anonymous Class Accesing Local Variables

If you look at my code below, you'll see I have declared int x = 0 in a method M(). I then declare an anonymous class within said method and declare int z = x. My question is that I though this would not be allowed, since x is defined in the encapsulating method which the anonymous class exists, and is not a constant. Maybe I am misunderstanding something. Could someone please help clear my confusion?

public class SomeClass {
public void someMethod(Super pObj) {}
}

public class Super {
    public Super() {}
    public void aMethod() {}
}

public class SubClass extends Super {

    public void M() {
        SomeClass someObject = new SomeClass();

        int x = 0;

        someObject.someMethod(new Super() {

            int z = x;  

            @Override public void aMethod() {}
        });
    }
}

Upvotes: 2

Views: 61

Answers (2)

Adam Ostrožlík
Adam Ostrožlík

Reputation: 1426

I have also used workaround witch wrapper final object. It this way, object is effectively final but you can change values in it.

final Counter counter = new Counter() ; in anonymous class you can do: counter. increaseValue() ;

Upvotes: -1

Maxim
Maxim

Reputation: 1254

The x variable is effectively final, so can be used in an anonymous class (starting with Java SE 8).

For additional info you can check this thread

Upvotes: 3

Related Questions