First, you *need* to declare it final if you want to reference it in an anonymous inner class.
Second, when working with legacy code, we often have to deal with very long methods (consider yourself lucky if you don't have to deal with such code). In such cases, declaring a local variable final can be of great help to understand the code.
For example, imagine that myFunction is 1500 lines long, and in line 1499 which reads
subStr = str.subString(2);
you occasionally get a NullPointerException. You think that str actually never should be null. With str not being final, you will have to look through the whole function to see whether it is assigned null somewhere. If you can declare it final without getting a compile time error, you instantly know that the problem isn't in the function itself - it the null value has already been passed to the function.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: May 17, 2004
Thanks. You menion 'First, you *need* to declare it final if you want to reference it in an anonymous inner class.'
Can you please tell me why it has such restriction?
Normally, if I do this public void aFunction(String str); this won't change the str passing in.
So even for the anonymous inner class, the function won't affect the class passing in too, Right?