Skip to main content

How to Create Immutable Class and Object in Java

How to create Immutable Class and Object in Java - Tutorial Example

Writing or creating immutable classes in Java is becoming popular day by day, because of the concurrency and multithreading advantages provided by immutable objects. Immutable objects offer several benefits over a conventional mutable object, especially while creating concurrent Java applications. An immutable object not only guarantees the safe publication of an object’s state but also can be shared among other threads without any external synchronization. In fact, JDK itself contains several immutable classes like String, Integer, and other wrapper classes.

For those who don’t know, immutable objects are those whose state cannot be changed once created. A good example is java.lang.String — once created, a String object cannot be modified. Any operation that seems to modify a String object (like trim(), toUpperCase(), etc.) actually results in a new object.
What is an immutable class in Java? Example

What is an Immutable Class in Java?

An immutable class is one whose object cannot be modified once created. Any modification will result in a new immutable object. The best examples to understand this concept are String (immutable) and StringBuffer (mutable). Here are some important characteristics of immutable classes:

  • The state of an immutable object cannot be modified after construction.
  • All fields of the immutable class should be final.
  • Object references must not leak during the construction process.
  • The class should be declared final to prevent inheritance.

    Builder design pattern explained

How to Write an Immutable Class in Java?

Below are the key rules to create an immutable class in Java:

  1. The state of the object cannot be modified after construction.
  2. All fields should be final to ensure they are assigned only once.
  3. Ensure proper construction to prevent object reference leaks.
  4. Declare the class final to avoid subclassing, which could break immutability.

Let's look at a simple example of creating an immutable class:

Example of Immutable Class

public final class Contacts {

  private final String name;
  private final String mobile;

  public Contacts(String name, String mobile) {
    this.name = name;
    this.mobile = mobile;
  }

  public String getName() {
    return name;
  }

  public String getMobile() {
    return mobile;
  }
}

In this example, the Contacts class is immutable because its state cannot be changed after the object is created. Both the fields (name and mobile) are final and assigned only once inside the constructor.

Handling Mutable Fields

Sometimes, you may need to include mutable fields (like Date) in an immutable class. In such cases, returning a copy of the mutable object is recommended to preserve immutability.

public final class ImmutableReminder {
  private final Date remindingDate;

  public ImmutableReminder(Date remindingDate) {
    if (remindingDate.getTime() < System.currentTimeMillis()) {
      throw new IllegalArgumentException("Cannot set a reminder for past time: " + remindingDate);
    }
    this.remindingDate = new Date(remindingDate.getTime());
  }

  public Date getRemindingDate() {
    return new Date(remindingDate.getTime());
  }
}

In this example, Date is a mutable object, but we preserve immutability by returning a clone of the Date object instead of returning the actual reference.

Benefits of Immutable Classes in Java

  • Immutable objects are inherently thread-safe and can be shared without synchronization in a concurrent environment.
  • They simplify development by removing the need for synchronization.
  • Immutable objects can be reused and cached for better performance.
  • They play a key role in writing functional programming code in Java.

However, immutability also has some downsides, like creating additional garbage due to the need for new objects whenever modifications are required.

Conclusion

In this article, we explored how to create immutable classes in Java, discussed their properties, and examined the benefits and challenges of using immutable objects. If you're working on concurrent applications, leveraging immutability can greatly simplify your code while improving safety and performance.

Comments

Popular posts from this blog

How to parse JSON with date field in Java - Jackson @JsonDeserialize Annotation Example

How to Parse JSON with Date Field in Java - Jackson `@JsonDeserialize` Annotation Example Parsing JSON in Java is a common task, but dealing with date fields requires a little extra attention. JSON treats everything as a string, but Java has strong typing, meaning dates need to be handled differently. In this post, we will see how to parse a JSON with a date field using Jackson, focusing on the `@JsonDeserialize` annotation. Example Scenario Let’s assume we have a simple JSON that includes a date field: ``` {   "name": "John Doe",   "birthDate": "2024-09-05" } ``` In Java, we might want to map this to a class with a `LocalDate` for `birthDate`. This is where Jackson's `@JsonDeserialize` annotation comes into play. Step-by-Step Example Step 1: Add Jackson Dependency First, make sure you have the Jackson dependency in your `pom.xml` if you’re using Maven: ``` <dependency>     <groupId>com.fasterxml.jackson.core</groupId>     &

Preparing for a Java Fresher Interview: Key Concepts and Tips

 When preparing a fresher graduate for a position involving Java technology, it’s important to gauge their understanding of fundamental concepts, problem-solving skills, and their ability to learn and adapt. Here are some questions and points that are important for freshers: Key Areas to Focus On: 1. Core Java Concepts:    - Object-Oriented Programming (OOP) principles: encapsulation, inheritance, polymorphism, and abstraction.    - Basic syntax and structure of a Java program.    - Data types, variables, operators, and control structures (loops, conditionals). 2. Advanced Java Concepts:    - Exception handling.    - Collections framework (List, Set, Map).    - Multithreading and concurrency basics.    - Input/Output (I/O) and serialization. 3. Java Development Tools and Environment:    - Knowledge of Integrated Development Environments (IDEs) like Eclipse or IntelliJ IDEA.    - Basic understanding of build tools like Maven or Gradle.    - Familiarity with version control systems like

java Interview Goal

                                                  Hi All,         I write this blog for Fresher  And  Experience  who have start Career In IT_Industry With  java Technology, I am not a professional blogger, I am  working  as Java Developer since last 2 years,   The main reason to write this blog is to share my Experience In Interviews. ABOUT THE AUTHOR           Nice to meet you, I’m Akshay Ingole. I’m a not a professional blogger ,  I am  working  as Java Developer since last 2 years,   The main reason to write this blog is to share my Experience In Interviews as well as share the topics that trending in java.   I hope It is Useful For All.