java - local variable made final in method of a class -- but why? -
today while searching piece of code google, came across 1 q/a blog, been said can declare local variable inside method of class final. however, author reluctant enough explain need/ benefit of doing so.
like
public class { private void show() { final string s="checking"; } }
i seek java gurus' educate me on this. in advance kind support , guidance.
best regards!
in addition other answers, making variable final
enables use of variable in inline implementation of classes , interfaces:
final string test = "test"; foo = new foo() { public void bar() { system.out.println(test); } };
edit: if beginner might worth pointing out variable in fact reference instance. when make variable final
in fact making reference constant, is, final variable can never refer other instance after initialization. makes no claims whether actual referenced instance constant.
for example, if final string[] foo = { "bar", baz" }
can foo[0] = "sheep"
though foo
final
. cannot reference foo
variable else, in foo = new string[]...
or foo = someotherarray
. has mutability , immutability , concepts akin final
, might worth investigating.
Comments
Post a Comment