Master java skills

Custom Immutable Classes

An immutable class is the one whose objects’ state cannot be changed once created. String class is one example of immutable class. All the wrapper classes are also immutable.

In this tutorial, we will learn to create a custom immutable class

Below are certain rules for immutable classes

  1. Declare the class as final so that it cannot be subclassed
  2. Make all the fields as private so that direct access is not allowed
  3. Make all the mutable fields as final so that their value cannot be changed once assigned
  4. Don’t provide setter methods for the properties
  5. Initialize all the fields using constructor performing deep copy
  6. Do the cloning of objects in the getter methods so that the copies are returned from them instead of the actual object references

Custom Immutable Class Example

package com.javatrainingschool;

import java.util.HashMap;
import java.util.Map.Entry;

public class Artist {
        
	//make all fields final
	private final int id;
	private final String name;
	private final HashMap<Integer, String> booksMap;
	
	//constructor using deep copy
	public Artist(int id, String name, HashMap<Integer, String> booksMap) {
		this.id = id;
		this.name = name;
		
		HashMap<Integer, String> booksMapCopy = new HashMap<>();
		for(Entry<Integer, String> entry : booksMap.entrySet()) {
			booksMapCopy.put(entry.getKey(), entry.getValue());
		}
		
		this.booksMap = booksMapCopy;
	}
	
	public int getId() {
		return this.id;
	}
	
	public String getName() {
		return this.name;
	}
	
	public HashMap<Integer, String> getIdNameMap(){
		return (HashMap<Integer, String>) booksMap.clone();
	}

	//tesing immutable class
	public static void main(String[] args) {
		
		HashMap<Integer, String> booksMap = new HashMap<>();
		booksMap.put(101, "Geetanjali");
		
		Artist a1 = new Artist(1, "Rabindranath Tagore", booksMap);
		
		//now the object referenced by a1 cannot have any other values than 1, Rabindranath Tagore and booksMap
		
		System.out.println(a1);
		
	}

	@Override
	public String toString() {
		return "Artist [id=" + id + ", name=" + name + ", booksMap=" + booksMap + "]";
	}	
}