An immutable class is one whose state can not be changed once created. There are certain guidelines to create an class immutable.
Guidelines to make a class immutable-
public final class FinalPersonClass { private final String name; private final int age; public FinalPersonClass(final String name, final int age) { super(); this.name = name; this.age = age; } public int getAge() { return age; } public String getName() { return name; } }
All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
What are the advantages of immutability?
The advantages are:
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
4) The best use of the immutable objects is as the keys of a map.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…