In this example, what value does declaring Object final
offer?
private void doSomethingClever(final Object o) {
}
In this example, what value does declaring Object final
offer?
private void doSomethingClever(final Object o) {
}
What this does is it allows someone else who comes along and visits your code to know the parameter cannot be changed. Resulting in a compilier error if they set a value.
That is to say that using it tells readers and the compiler that that parameter will not be modified in the method.
Useful Links:
You will not be able to assign to o
in the method.
It is very useful when having an inner class such as listener or some runnable accessing this local variable.
To be honest I don't really see the point of using final in method parameters. final will only guarantee that the variable will not be pointing to another object, not that the object itself will not be immutable... You can change the state of Object o, you just cant assign o to another object like B
o = new Object();
or
Object b = new Object();
o=b;
but invoking
o.doSomething();
is just fine. So why clutter the code with ugly final keywords everywhere??
As for performance optimization I believe that modern compilers will analyze and optimize the code even without the final keyword in method parameters. Would anyone care to correct me on this as I'm not 100% sure about that point!