In a Java interview Q&A list I have, it says that, in Java you can make an object immutable in three ways. One of the ways is:
Ensure that methods can't be overridden by either making the class final (Strong Immutability) or making your methods final (Weak immutability).
How is it that making methods final is considered less immutable than making the class final? Also, what is meant by strong immutability and weak immutability ?
An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications.
The only real disadvantage of immutable classes is that they require a separate object for each distinct value.
Immutable objects offer a number of advantages for building reliable applications. As we don't need to write defensive or protective code to keep application state consistent, our code can be simpler, more concise, and less error-prone than when we define mutable objects.
Improved safety - Once you've verified the state of an immutable object, you can be confident that it will stay safe and valid (no background process will be able to change it without you knowing) Better caching - You can cache references to immutable objects since they won't change.
Because the Liskov Substitution Principle states that a subclass instance can be substituted wherever a superclass instance is expected, without changing the semantics from the caller's point-of-view. A subclass could introduce mutable behaviour, thus violating the LSP.
On the one hand, final methods (and private member variables) limit the scope for altering the semantics as seen directly via the superclass interface. On the other hand, a mutable subclass could introduce violations indirectly.
For example, perhaps the caller framework doesn't bother cloning or using synchronisation in multi-threaded scenarios, based on the immutability assumption. This would cause major issues when applied to a mutable subclass, but not due to any semantic change to the superclass interface.
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