java - Why anonymous internal class calls an external object when the external object is declared with the final -


this question has answer here:

final arrayadapter adapter = new arrayadapter(...); listview.setonitemclicklistener(new adapterview.onitemclicklistener(){     @override     public void onitemclick(adapterview<?> parent,view view,int position,long id){         word word = adapter.getitem(position);     } }); 

i can't understand why anonymous inner class calls "adapter" object should declared "final" ? rule? should remember that? know variable declared final save reference without changing. in example above, there no change of reference, call method on final object.

that's because you're trying access adapter in listener (and don't know when happen). so, need declare final because means reference same whenever callback listener. when function destroyed, non-final references declared inside function destroyed. then, reference try access later in listener not exist anymore.

so have 2 solutions: declare final (and keep reference after function "destroyed") or declare global.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -