Monday, May 12, 2014

How to create immutable class in Java

What is an immutable class?
An immutable class is a class which once created, its contents can not be changed. Modification of the object will lead to creation of new instances. e.g. String class

How to create an immutable class?
Below are important guidelines to create an immutable class.
  • Declare the class as final so it can’t be extended.
  • Make the properties of the class final and private so that their values can be assigned once and they are not directly accessible from outside world.
  • Set the values of properties using constructor only.
  • Do not provide any setters for these properties.
  • If the class has any mutable object fields, then they must be defensively copied when they pass between the class and its caller.




public final class Student {

     private final String name;
     private final int age;
     private final List books;

     public Person(String name, int age, List books) {
         this.name = name;
         this.age = age;
         this.books = new ArrayList(this.books);
     }

     public String getName() {
         return this.name;
     }

     public int getAge() {
         return this.age;
     }

     public Collection getBooks() {
         return Collections.unmodifiableList(this.books);
     }
}

What are the benefits of using immutable classes?
Benefits are as follows:
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 best use of the immutable objects is as the keys of a map.


List examples of immutable classes.
All wrapper classes in java.lang are immutable like String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger.

No comments :

Post a Comment