Why it says that "Cannot refer to a non-final variable i inside an inner class defined in a different method"?

Khawar Raza picture Khawar Raza · Oct 21, 2011 · Viewed 34.8k times · Source

I have button click listener and in onCreate() method I have a local variable like

 onCreate() {

 super.onCreate();

 int i = 10;

 Button button = (Button)findViewById(R.id.button);

 button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            i++;
        }   
    });

Why java asks for to make me final ?

Answer

birdy picture birdy · Oct 21, 2011

When the onCreate() method returns, your local variable will be cleaned up from the stack, so they won't exist anymore. But the anonymous class object new View.OnClickListener() references these variables. Of cause it's wrong behavior so java don't allow you to do this.

After it is final it becomes a constant. So it is storing in the heap and can be safely used in anonymous classes.