Immutable classes

An object is said to be mutable when the state of the object can be changed E.x. through the setter methods mostly (of course there are other alternatives to change the state, which we will understand once we step through the guidelines of creating an immutable class). Immutable objects are objects whose state cannot be changed after they are created. Once created their state remains the same till the lifetime of the application (rather every life of the application).

Why would one create an immutable objects?  

  • Immutability objects find their use in concurrent applications/ multi-threaded applications, such an object is always thread safe which means threads wont see an inconsistent state of such an object,so you don't have to synchronize access to them across threads.
  • They also are good candidate in Hash based collections like HashSet  (they need to override equals and hashCode methods). 
  • You can freely share and cache references to immutable objects without having to copy or clone them; you can cache their fields or the results of their methods without worrying about the values becoming stale or inconsistent with the rest of the object's state. 
  • Wrapper classes in java language like Integer, Short, String etc are immutable. 

    So how would you create an Immutable class or what are steps to create one?
    1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
    2. Make all fields final and private.
    3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
    4. 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.


    Popular posts from this blog

    How does HashMap work in Java

    Am back...Should we start blogging about Java 8 and more