java - Why Local Inner class requires local variable Final? This Variable is in same method in which Local Inner class define -
java - Why Local Inner class requires local variable Final? This Variable is in same method in which Local Inner class define -
this question has reply here:
cannot refer non-final variable within inner class defined in different method 19 answerswhy local inner class requires local variable final? variable in same method in local inner class define. if not utilize final keyword give compilation error. please check next programme on ideone
class localinnerclasstest2 { private string x="outer2"; public static void main(string [] args){ localinnerclasstest2 test=new localinnerclasstest2(); test.dostuff(); } void dostuff(){
//why next local variable "final string z" requires final keyword
final string z="local variable"; class myinner { public void seeouter(){ system.out.println("outer x "+x); system.out.println("local variable z "+z); } } myinner my=new myinner(); my.seeouter(); }
}
because inner class gets re-create of environment available when instantiated.
if don't declare z
final have situation following:
string z = "variable"; class myinner { public void seeouter(){ system.out.println("outer x "+x); system.out.println("local variable z "+z); } } myinner my=new myinner(); z = "another value"; my.seeouter();
but context myinner
created upon instantiation, lead seeouter
accessing different value of z
(bound before changed) , misleading (and wrong since wouldn't expect it).
java inner-classes
Comments
Post a Comment