Immutable class :
A class whose contents can not be changed once created.
Immutable object
: An object whose state can not be
changed once constructed.
To create an immutable class following steps should be followed:
- Create class as a final.
- Make all the members of the class as private and final.
- Set the values of members using constructor or in static block only.
- Don’t provide any methods that can change the state of the object in any way (i.e not only setter methods, but also any method which can change the state).
- 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.
E.g.
public final class Person {
public final class Person {
private final String name;
private final int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
private final int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
Immutable classes in java are :
All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigInteger
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigInteger
Note : Immutable objects are
automatically thread-safe. Because the state of the immutable objects can not
be changed once they are created.
No comments:
Post a Comment