While there are many reasons to use the \'final\' keyword in Java, one of the ones I keep hearing over and over again is that it makes your code more secure. While this seem
It's not 'security' in the sense of 'withstanding an attack'; it's more like 'harder to mess up by mistake'.
I prefer the word 'safety'; i feel its more like preventing an accident, not malice.
It is more about "changing" the stuff rather than "securing". The final keywords simply puts away the ability to change/modify/extend any method.
Final keyword is usually used to preserve immutability. To use final for classes or methods is to prevent linkages between methods from being broken. For example, suppose the implementation of some method of class X assumes that method M will behave in a certain way. Declaring X or M as final will prevent derived classes from redefining M in such a way as to cause X to behave incorrectly. It secures objects and methods from getting manipulated. But as for cryptography purpose, using final keyword is not the solution
Java's final
keyword is not used for this kind of security. It is not a substitute for what would normally require a cryptographic solution.
What is usually meant by "security" in these kinds of discussions is the concept of a secure object model - that is to say an object model that cannot be manipulated by consumers for purposes unintended by the original author of the class.
I'm not sure I would rely on language constructs for added security in my system.
I don't think that making a field final would add security against malicious attacks (more likely against mistakes and of course threading issues). The only "real form" of security is that if you have a final constant field it might get inlined at compilation so changing its value at runtime would have no impact.
I've heard of final and security more in the context of inheritance. By making a class final you can prevent someone from subclassing it and touching or overriding its protected members, but again I would use that more to avoid mistake than to prevent threats.
In general final, private and other such constructs should be considered more as general statements of preference, rather than strictly enforced security.
However, if you control the JVM the process is running on (say you run code provided by others on your JVM) then final and private do indeed provide security - coupled with Java's SecurityManager. The things you can do via reflection to get around these restrictions can be prevented.
What you can't do is ship code to run on someone else's JVM and think that you hide anything this way.
Edit: Tom reminds me that Serialization attacks (that is deliberately providing bad binary streams of serialized data) can also be prevented in part by proper use of final fields. Effective Java has more such examples.