Java Immutable class
All the wrapper classes of primitive date types are immutable, immutable is a concept whose state or values cannot be changed once they are declared. If we try to change any value of the immutable class objects then instead of changing its original value it will create a new Object of same type and return with the new value which we trying to change.
To implement Immutable Class in Java we need to follow the below steps.
- The class should not be extended, this can be done using final keyword
- The class should not allow setter method, this can be done by not using any assigning methods.
- Make sure all the fields of Immutable class are final.
- In case if your using customized class object as a field in Immutable class, perform the deep copy.
Immutable class example
import java.util.Date; final class ImmutableClass{ private final int id; private final String name; private final String address; private final Date dob; public ImmutableClass(int id, String name, String address,Date dob) { this.id = id; this.name = name; this.address = address; this.dob=dob; } public int getId() { return id; } public String getName() { return name; } public String getAddress() { return address; } public Date getDob() { return new Date(); } @Override public String toString() { return "ImmutableClass [id=" + id + ", name=" + name + ", address=" + address + ", dob=" + dob + "]"; } } public class ImmutableClassExample { public static void main(String ar[]) { ImmutableClass immutableClass=new ImmutableClass(1, "std1", "addr1", new Date()); System.out.println(immutableClass); } }