Why Java inner classes require "final" outer instance variables? -
this question has answer here:
final jtextfield jtfcontent = new jtextfield(); btnok.addactionlistener(new java.awt.event.actionlistener(){ public void actionperformed(java.awt.event.actionevent event){ jtfcontent.settext("i ok"); } } );
if omit final
, see error "cannot refer non-final variable jtfcontent inside inner class defined in different method".
why must anonymous inner class require outer classes instance variable final in order access it?
well first, let's relax, , please put gun down.
ok. reason language insists on cheats in order provide inner class functions access local variables crave. runtime makes copy of local execution context (and etc. appropriate), , insists make final
can keep things honest.
if didn't that, code changed value of local variable after object constructed before inner class function runs might confusing , weird.
this essence of lot of brouhaha around java , "closures".
note: opening paragraph joke in reference all-caps text in original composition of op.
Comments
Post a Comment