Immutable Classes In Java

Java Spring Decoded
Javarevisited
Published in
2 min readApr 10, 2023

What are Immutable Classes ?

public class Immutable {
int x;
String y;

}

As we can see in this class , we have two fields , Once we initialized the object of this class , both of these fields will have a state

x = 0;

y = null;

Immutability of a class refers to the property that once we initialized a class , which means once our objects got a state , we can’t change that state.

How can we make our class Immutable ?

final class Immutable {
private final int x;
private final String y;

public Immutable(int x, String y) {
this.x = x;
this.y = y;
}
}
  1. Our member variable should be private to block access to edit it by some other client class.
  2. Our member variable should be final to ensure that no state change happen of the object as final ensures a single assignment and no reassignment.

3. Either we can make our class public to prohibit any classes from extending it or we can make our methods final so that no child class can override it and change the state of objects . It is preferred to make the final class as it restricts any kind of alteration to objects state .

What if there are Immutable field Inside a Mutable Class ?

import java.util.List;

final class Immutable {
private final int x;
private final String y;

private final List<Integer> numbers;

public Immutable(int x, String y, List<Integer> numbers) {
this.x = x;
this.y = y;
this.numbers = numbers;
}

public int getX() {
return x;
}

public String getY() {
return y;
}

public List<Integer> getNumbers() {
return numbers;
}
}

As we can see here , the numbers is a list of Integer , But the numbers list is not immutable we can alter the states of numbers list returned by the getter.

List<Integer> integers = new ArrayList<>();
integers.add(10);
Immutable immutable = new Immutable(1,"a", integers);
immutable.getNumbers().add(20);

Here we can alter the state of our immutable class , to prevent this , we should always return a new deep copied instance of mutable fields inside of immutable class.

final class Immutable {
private final int x;
private final String y;

private final List<Integer> numbers;

public Immutable(int x, String y, List<Integer> numbers) {
this.x = x;
this.y = y;
this.numbers = numbers;
}

public int getX() {
return x;
}

public String getY() {
return y;
}

public List<Integer> getNumbers() {
List<Integer> numbers = new ArrayList<>();
for(Integer integer : this.numbers) {
numbers.add(integer);
}
return numbers;
}
}

Here we are returning a new deep copied version of our mutable field.

We have to remove any kind of nested mutability using this method to ensure the immutability of our Class.

--

--

Java Spring Decoded
Javarevisited

All Articles related to java , spring , Backend Development and System Design.