Overview Of Immutable class

Overview Of Immutable class

Immutable class means a class whose object cannot be modified once created. If we do any modification on immutable object will result in another immutable object. String class, Integer class etc. are the immutable classes in Java.

How to create Immutable class in Java

  • Make the class final
  • Make all member variables of class final
  • Provide constructor to set values
  • No methods that modify state i.e. no setter methods
  • Immutable Objects are thread safe, because the values will never change.
  • Require no synchronization
Write a code for immutable class as follows

package com.test.demo;

public final class ImmutableClassDemo {
	
	//fields are made private and final to restrict outside access
	private final String name;
    private final String mobile;
    private int age;

    public ImmutableClassDemo(String name, String mobile, int age) {
        this.name = name;
        this.mobile = mobile;
        this.age = age;
    }
    
  //provide only getters
	public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }
    
    public int getAge() {
		return age;
	}
 
    @Override
    public String toString() {
    	
    	return name+ " " + mobile+ " " +age;
    }

}
Create main class to run the immutable class write code as follows

package com.test.demo;

public class TestMain{
	
	public static void main(String[] args) {
		
		ImmutableClassDemo immutableClassDemo = new ImmutableClassDemo("Java", "89833333",25);
		System.out.println(immutableClassDemo);
			
	}
}