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 seems to make sense in this trivial case:
public class Password { public final String passwordHash; ... }
With the final keyword, you would expect that no malicious code would be able to change the variable passwordHash. However, using reflection it is possible to change the final modifier on the passwordHash field.
So does 'final' provide any real security, or is it just placebo?
Edit: There is some really interesting discussion, and I wish I could accept more than one answer. Thanks everyone for your input.
The final keyword has a different purpose when applied to classes and methods. When we apply the final keyword to a class, then that class cannot be subclassed. When we apply it to a method, then that method cannot be overridden. There are no reported performance benefits of applying final to classes and methods.
Final Method in Java The Method with Final Keyword cannot be overridden in the subclasses. The purpose of the Final Method is to declare methods of how's definition can not be changed by a child or subclass that extends it. The above example of the Final Method generates a compile-time error.
When a final modifier is used with a class then the class cannot be extended further. This is one way to protect your class from being subclassed and often sensitive classes are made final due to security reasons. This is also one of the reasons why String and wrapper classes are final in Java.
In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can't be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.
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' as I feel it's more like preventing an accident, not malice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With