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

  • Write Getter method for all the variables in it.

Advantages of Immutable Object are:

  • Immutable Objects are thread safe, because the values will never change.

  • Require no synchronization

package com.javabykiran.immutableclass;

public class JbkImmutableClassDemo {
    private final String name;
    private final String mobile;
    private final int age;

    public JbkImmutableClassDemo(String name, String mobile, int age) {
	super();
	this.name = name;
	this.mobile = mobile;
	this.age = age;
    }

    public String getName() {
	return name;
    }

    public String getMobile() {
	return mobile;
    }

    public int getAge() {
	return age;
    }

    @Override
    public String toString() {
	return "JbkImmutableClassDemo [name=" + name + ", mobile=" + mobile + ", age=" + age + "]";
    }

}
package com.javabykiran.immutableclass;

public class JbkTest {
    public static void main(String[] args) {
	JbkImmutableClassDemo jbk = new JbkImmutableClassDemo("JavaByKiran", "88888888", 30);
	System.out.println(jbk);
    }
}