Immutable Objects in Java - DevDummy

Latest

Coding Hacks, Shared ...

Tuesday, September 12, 2017

Immutable Objects in Java

What is an Immutable Object ?

As per the Java Reference Documentation,
"An object is considered immutable if its state cannot change after it is constructed"
Simply an immutable class is a class whose properties can not be modified after creation. That means at creation, all of the instance data is provided and remain unchanged till the destruction of the objects.

Why Immutable Objects ?
Immutable classes are great for concurrent applications. As per their immutable nature, they help to maintain the application in non-corrupted and consistent behavior as the state of the instances can not be changed.

Concerns
Immutable classes are easy to design, develop and use as they are more error resistant and secure due to the immutability. However programmers reluctant to use them due to the re -usability limitation. Also it may have an performance impact on object creation than reusing. However with the latest sophisticated compilers, the cost of creation is a minimal. Also the provided capabilities and the advantage of immutability can be adopted beyond the re-usability as per the need. 

Rules for Writing Immutable Classes
  • All filelds are private & final
  • Class can not be extended
  • No public method can change the state
Examples
  • String
  • Boxed primitives like Integer, Long and etc.
  • BigInteger
  • BigDecimal. 
Key Points
  • Immutable objects are thread-safe from nature.
  • No synchronization is required on concurrent applications
  • Can be shared with no concerns
Q & A
  • All classes should be immutable ?
    • Yes it is  unless it is really required to change its state later
  • How does this String append is working ?
    • New String object is created with the given value and the reference is updated to the new instance isolating the old object.

No comments:

Post a Comment