Immutable Class in Java: from 0 to 1…
Immutability is a feature that means unchangeable or unmodified.
In Java, the concept of the Immutable class says once an object is created we can not change its content. In the process of creating an immutable class final keyword plays an important role.
All the wrapper and String classes are immutable.
Rules for creating an immutable class
- Make class as final — so the inheritance will not be possible and child class cannot be created for changing the property of parent/actual class.
- Make variables final — because of this any kind of changes can not happen to the variables, all variables will be initialized only once from the constructor.
- The class must not contain any public setter method — Hence outside modification changes will be stopped.
Example -
- String is an immutable class. If we create an object of string and try to reassign value then a new object will be created and it will point to the new one.
String name = “Rahul”;
name = “Kamal”;
The new value of name will be Kamal. And the older one(Rahul) will be unrefereed.
2. Custom Immutable Class
Use-case : Once Database connection object is created with its configuration values you might not need to change its state where you can use an immutable class.
Purpose/Benefits of Immutable Class-
- Immutable objects offer facility to building reliable applications. Therefore we don’t need to write defensive or protective code to keep application state consistent, code can be simpler, more concise, and less error-prone than when we define mutable objects.
- Thread safety can easily achievable.
- Immutable classes can be used for cashing purpose for this we don’t need synchronization for this
- Simpler to develop. You guarantee that no subclass will exist if an object is immutable. E.g. a String class.
You can find program here: https://github.com/arpitbhatt027/core-java-programs/blob/master/src/basic_programs/User.java