How to Make Immutable Object in Java

Connect with

Immutable Objects in JavaMaking Java an immutable object is very simple and a little bit tricky. Immutable objects in java are simply objects whose state (the object’s data) cannot change after construction.

1. Overview of Immutable Objects In Java

In general, classes in an application are designed to carry data and behavior. Sometimes, a class may be designed in such a way that its instances can be used just as carriers of related data without any specific behavior. Such classes can be called data model classes and instances of such classes are referred to as data objects. In general, in the java environment, DTO (Data Transfer Object) can be made immutable to access in a multithreaded environment so the immutable version of the DTO objects can safely be used in a multithreaded environment.

2. Important point to make a class Immutable in Java

You must know java immutable objects if you are working in a multithreaded application where you update the state by multiple threads. The key points for making immutable java object as follows:

  • Set state via Constructor: All instance variables (state/property) must be set in the constructor alone. No other method should be provided to modify the state of the object. The constructor is automatically thread-safe and hence does not lead to problems.
  • Declare final class: It may be possible to override class methods to modify the state. In order to prevent this, declare the class as final. Declaring a class as final does not allow the class to be extended further.
  • final property/attribute: All instance variables should be declared final so that they can be set only once, inside the constructor.
  • Associated Object: If any of the instance variables contain a reference to an object, the corresponding getter method should return a copy of the object it refers to, but not the actual object itself.

3. Which classes are Immutable in Java?

In all the languages few classes are made intentionally so as in Java too. classes that are immutable, all of the java.lang package wrapper classes are immutable: String, Boolean, Byte, Character, Double, Float, Integer, Long, Short.

4. When to use Java immutable Objects?

We usually design our class for making objects immutable for only one reason that is, no client can change the state of any property/attribute. And this can be applicable for a multithreaded environment or a single-threaded environment where you do not want to change the state of that object while accessing.
If you think carefully, you can find any class in java either for behaviour or for data. And Immutable objects pattern for data, not for behaviour.

Custome.java

/**
 *
 */
 package com.mysoftkey.test;/**
 * This class is used as a DTO (Data Transfer Object) or Domain model object
 * which carries the Customer related data from one tier to another tier
 * in the network.
 *
 * @author Ranjeet Jha
 *
 */
 public final class Customer {
  // Property/State
   private final String name;
   private final Address address;
  
   //Constructor
   public Customer(String name, Address add) {
   this.name = name;
   this.address = add;
}

 public String getName() {
 return name;
 }

 public Address getAddress() {
 //return a copy of the Address object
 return (Address) address.clone();
}
}

Address.java

/**
 *
 */
 package com.mysoftkey.test;
import java.io.Serializable;

/**
 * This class is used as a DTO (Data Transfer Object) or Domain model object
 * which carries the address related data from one tier to another tier in
 * network. This object can be cloned as {@link Cloneable} interface is implemented.
 *
 * @author ranjeet.kr@gmail.com
 *
 */
 public class Address implements Serializable, Cloneable {

 // property for this class to make immuatable
 private String line1;
 private String line2;
 private String city;
 private String state;
 private String country;
 private String zipCode;

 public String getLine1() {
   return line1;
 }

 public String getLine2() {
   return line2;
 }

 public String getCity() {
 return city;
 }

 public String getState() {
 return state;
 }

 public String getCountry() {
 return country;
 }

 public String getZipCode() {
 return zipCode;
 }

 public void setLine1(String line1) {
 this.line1 = line1;
 }

 public void setLine2(String line2) {
 this.line2 = line2;
 }
 public void setCity(String city) {
 this.city = city;
 }

/**
 * @param state
 * the state to set
 */
 public void setState(String state) {
 this.state = state;
 }
 public void setCountry(String country) {
 this.country = country;
 }

 public void setZipCode(String zipCode) {
 this.zipCode = zipCode;
 }

 public Object clone() {
 try {
 return super.clone();
 } catch (CloneNotSupportedException e) {
 throw new Error("This should not occur since we implement Cloneable");
 }
 }
}

Video version of this post: Immutable Objects Design Patterns

Immutable Objects design patterns

Your comment is welcome to improve this post on immutable object patterns. 🙂 cheers and happy learning how to make java immutable objects pattern. Thank you! 🙂


Connect with

13 thoughts on “How to Make Immutable Object in Java”

  1. this is good demo of making a immutable object in java , understand this quickly. thanks a lot to explain easily …

Leave a Reply to ValeriRire Cancel Reply

Your email address will not be published. Required fields are marked *