How to create immutable class in Java? Why immutable class should be marked final? What are the advantages and disadvantages of immutable classes?

What is immutable class: A class is immutable if no method of the class can mutate its objects. For example, the String class is immutable. An immutable object cannot be modified once it is constructed. The information contained in immutable object is provided at the time of object creation and it is fixed for the lifetime of the object. If you need to modify the object, you can always create a new one that contains the modifications, but the existing won't change. Because immutable objects cannot be modified, therefore, they are thread-safe and all threads will see the same consistent state of the object. There are examples of immutable built-in Java classes such as the primitive wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, and Boolean), and BigInteger and BigDecimal.

Rules to create immutable class: In order to make a Java class immutable, follow these rules.

  1. Do not implement setter methods (known as mutators) that can modify the state of the object.
  2. Declare all fields (data members) private and final. private, so that they cannot be accessed outside the class; and final, so that they cannot be changed after construction.
  3. Declare the class final. This ensures that the class can't be extended. If the class is not marked final, it might be possible for someone to extend the class and mutate its members.
  4. If the class has any fields that refer to mutable objects, ensure that clients of the class cannot obtain references to these objects. To do that, don't provide methods that modify the mutable objects. Don't share references to the mutable objects. In case you need to return a mutable object then create copy of your internal mutable object to avoid returning the original object in your methods.

Advantages of immutable objects: An immutable object remains in exactly one state, the state in which it was created. Therefore, immutable object is thread-safe. They cannot be corrupted by multiple threads accessing them concurrently. This is far and away the easiest approach to achieving thread safety.

Disadvantages of immutable objects: Creating an immutable class seems at first to provide an elegant solution. However, whenever you do need a modified object of that new type you must suffer the overhead of a new object creation, as well as potentially causing more frequent garbage collections. The only real disadvantage of immutable classes is that they require a separate object for each distinct value. Creating these objects can be costly, especially if they are large.

For reader's reference, the following piece of Java code demonstrates an immutable class ImmutablePerson.

/* ImmutablePerson.java */
 
//immutable class is declared final
public final class ImmutablePerson 
{
  //fields are made private and final to restrict outside access
  private final String fname;
  private final String lname;
  private final int age;
 
  public ImmutablePerson(String fname, String lname, int age)
  {
    this.fname = fname;
    this.lname = lname;
    this.age = age;
  }
 
  //provide getters, no mutators
  public String getFname()
  { 
    return this.fname;
  }
 
  public String getLname()
  { 
    return this.lname;
  }
 
  public int getAge()
  {
    return this.age;
  }
}

Hope you have enjoyed reading about creating immutable classes and objects in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!




Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

Bees 'go online' in ManchesterPosted on Friday September 22, 2017

Rory visits a beekeeper in Manchester who is gluing wireless chips to his bees.

The long wait for a Persian iPhone keyboardPosted on Friday September 22, 2017

The new Apple's iOS has Persian keyboard. BBC Persian's Sam Farzaneh discusses why it is an important feature.

Uber London loses licence to operatePosted on Friday September 22, 2017

Ride-hailing app Uber is "not fit and proper" to operate in London, the transport regulator says.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×