It says in this article that:
Making a class final because it is immutable is a good reason to do so.
I'm a bit puzzled by this... I understand that immutability is a good thing from the POV of thread-safety and simplicity, but it seems that these concerns are somewhat orthogonal to extensibility. So, why is immutability a good reason for making a class final?
No, it is not mandatory to have all properties final to create an immutable object. In immutable objects you should not allow users to modify the variables of the class. You can do this just by making variables private and not providing setter methods to modify them.
By declaring immutable classes final, we impose a guarantee that malicious subclasses capable of changing the state of the object and violating assumptions that clients often make regarding immutability, are not a concern.
final modifier is applicable for variable but not for objects, Whereas immutability applicable for an object but not for variables. By declaring a reference variable as final, we won't get any immutability nature, Even though reference variable is final.
The problem with an immutable class not being final is that, subclasses may not be immutable. Here is an example from the Java API, java. lang. String is immutable and final, if a string is passed to one of your methods you can be sure that it will remain in a consistent state.
The explanation for this is given in the book 'Effective Java'
Consider BigDecimal
and BigInteger
classes in Java .
It was not widely understood that immutable classes had to be effectively final when BigInteger
and BigDecimal
were written, so all of their methods may be overridden. Unfortunately, this could not be corrected after the fact while preserving backward compatibility.
If you write a class whose security depends on the immutability of a BigInteger or BigDecimal argument from an un-trusted client, you must check to see that the argument is a “real” BigInteger or BigDecimal, rather than an instance of an un trusted subclass. If it is the latter, you must defensively copy it under the assumption that it might be mutable.
public static BigInteger safeInstance(BigInteger val) { if (val.getClass() != BigInteger.class) return new BigInteger(val.toByteArray()); return val; }
If you allow sub classing, it might break the "purity" of the immutable object.
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