Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong immutability vs weak immutability in Java?

Tags:

java

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 ?

like image 523
Caffeinated Avatar asked Aug 02 '15 14:08

Caffeinated


People also ask

What is immutability in Java?

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.

What is disadvantages of immutable class in Java?

The only real disadvantage of immutable classes is that they require a separate object for each distinct value.

What is the advantage of immutability in Java?

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.

What is the main advantage of immutable 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.


1 Answers

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.

like image 118
Oliver Charlesworth Avatar answered Nov 08 '22 06:11

Oliver Charlesworth