java - Why is final needed inside a method but not inside a class -


in android if i'm updating variable inside listener, e.g. ondraglistener, either need make variable final if it's declared inside method.

private void mymethod() {    final int[] = {null};     mf.setondraglistener(new touchablewrapper.ondraglistener() {        @override        public void ondrag(motionevent motionevent) {             map.setmylocationenabled(false);            log.d("map", "stopped location , remove drag listener");            if (motionevent.getactionmasked() == motionevent.action_up) {                 //stop restartlocation if it's running                 if (restart[0] != null) {                    restart[0].cancel = true;                }                restart[0] = new restartlocation();                restart[0].start();            }        }    }); } 

or if it's outside of method doesn't need final.

private restartthread restart; private void mymethod() {      mf.setondraglistener(new touchablewrapper.ondraglistener() {        @override        public void ondrag(motionevent motionevent) {             map.setmylocationenabled(false);            log.d("map", "stopped location , remove drag listener");            if (motionevent.getactionmasked() == motionevent.action_up) {                 //stop restartlocation if it's running                 if (restart != null) {                    restart.cancel = true;                }                restart = new restartlocation();                restart.start();            }        }    }); } 

i'm curious why final needed inside method, not outside of method. can shed light on this?

in java, anonymous inner classes can refer finalvariables in enclosing scope.

see the doc.

from java 8 onwards, enough if variable "effectively final", meaning not required explicitly declare final, compiler error if attempt reassign variable accessed anonymous inner class.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -