Java Program to Create an Immutable Class

Java Program to Create an Immutable Class

What is Immutable class in  Java ?

An immutable class in Java is a class that cannot be modified once it is created. This means that the state of an object of an immutable class cannot be changed after it is constructed. Immutable classes are often used when the state of an object needs to be shared across multiple threads, as they can be safely accessed without the need for synchronization or locking. Examples of immutable classes in the Java standard library include String and the wrapper classes for primitive types (e.g. Integer, Long).

Immutable class in Java :

An immutable class in Java is a class that once an object is created, it cannot be modified. This means that the state of an object of an immutable class cannot be changed after it is constructed.

Steps to create an immutable class in Java :

  1. Make the class final, so that it cannot be subclassed.
  2. Make all fields private and final, so that they cannot be modified once the object is created.
  3. Do not provide any setter methods, so that the fields cannot be modified from outside the class.
  4. Make sure that the class does not have any mutable instance variables.
  5. If the class has any mutable objects as fields, return new copies of these objects, instead of the original objects.

Use of Immutable classes :

Immutable classes are often used when the state of an object needs to be shared across multiple threads, as they can be safely accessed without the need for synchronization or locking. They also provide a simple and predictable way to manage the state of an object, and are useful in functional programming. Examples of immutable classes in the Java standard library include String and the wrapper classes for primitive types (e.g. Integer, Long).

In addition to that, the constructor should create a new instance of all the mutable fields, so that any modifications made to those fields in the caller won’t affect the internal state of the immutable object.

Example 1 :

Run

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

final class MyImmutableClass {
    private final int x;
    private final String y;
    private final List<Integer> z;

    public MyImmutableClass(int x, String y, List<Integer> z) {
        this.x = x;
        this.y = y;
        this.z = new ArrayList<>(z); // creating a new instance of the list to prevent external modifications
    }

    public int getX() {
        return x;
    }

    public String getY() {
        return y;
    }

    public List<Integer> getZ() {
        return new ArrayList<>(z); // returning a new copy of the list to prevent external modifications
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the immutable class
        MyImmutableClass obj = new MyImmutableClass(1, "hello", Arrays.asList(1, 2, 3));

        // Accessing the fields of the immutable object
        System.out.println("x: " + obj.getX());
        System.out.println("y: " + obj.getY());
        System.out.println("z: " + obj.getZ());

        // Attempting to modify the fields of the immutable object
        // This will not work as the fields are private and final
        // obj.x = 2;
        // obj.y = "world";
        // obj.z.add(4);
    }
}

Output :

x: 1
y: hello
z: [1, 2, 3]

Explanation:

In this example we have  created an immutable class called MyImmutableClass. It has three fields: x, y, and z, which are all private and final. This means that the values of these fields can only be set in the constructor and cannot be modified afterwards.

The class has a constructor that takes three arguments: an int value for x, a String value for y, and a List of Integer values for z. In the constructor, the passed values are assigned to the corresponding fields. Also, it creates a new instance of the list z using the ArrayList class constructor, this is done to prevent external modifications.

The class also has three getter methods: getX(), getY(), and getZ(), which return the values of the fields x, y, and z, respectively. The getZ() method also returns a new copy of the list z using new ArrayList<>(z) this also to prevent external modifications.

The Main class creates an instance of the MyImmutableClass using the constructor, it then accesses the fields of the object using the getter methods and prints the values.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription