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-
- Create a final class.
- Set the values of properties using constructor only.
- Make the properties of the class final and private
- Do not provide any setters for these properties.
- If the instance fields include references to mutable objects, don’t allow those objects to be changed:
- Don’t provide methods that modify the mutable objects.
- Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
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.
Hi ,
I am confused little bit about this example . Actually I want to know from this example that it is in bound service or Out bound service .
In bound