How to create Immutable class in java
Immutable class is a class which once created, its contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class
Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
All wrapper classes in java.lang are immutable
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
Create a final class.
public final class FinalPersonClass {
}
Set the values of properties using constructor only.
public final class FinalPersonClass {
public FinalPersonClass(final String name, final int age) {
this.name = name;
this.age = age;
}
}
Make the properties of the class final and private
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;
}
}
Do not provide any setters for these properties.
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;
}
}
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.
0 Comment(s)