How to create Immutable Class in Java

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags , with Leave a comment on How to create Immutable Class in Java

creating the Immutable class in Java with simple source code example

We have heard the word “Immutable class” lots of time in Java. The best example is class “String“. Immutable class is the class whose value cannot be changed throughout the life cycle. We cannot change the content of String class, everytime new reference is created when we change the content, that is the basic difference between String and StringBuffer Class.
In this article, i will explain the step by step process to create the custom Immutable class in Java.
Our class should not able to derived and for that we will declare our class as final. The values cannot be change and thats why we will declare all the variables as final and we will provide only the getter methods as we cannot write setters because of final variables.
So to summarize, following steps needs to be taken:

  1. declare class as final
  2. declare all variables as final
  3. provide constructor to set the values
  4. provide getter

Source code:

package in.shivasoft.demo;

final class Immutable
{
	private final int val1;
	private final String val2;

	public Immutable(int a, String s)
	{
		val1 = a;
		val2 = s;
	}
	public int getVal1()
	{
		return val1;
	}
	public String getVal2()
	{
		return val2;
	}
}

public class ImmutableClassDemo {
	public static void main(String[] args) {
		Immutable obj = new Immutable(10, "ShivaSoft ...the supreme solution");
		System.out.println(obj.getVal1());
		System.out.println(obj.getVal2());
	}
}

Output :

10
ShivaSoft …the supreme solution

Related posts