How we can create our own immutable class in java?

In the previous tutorial, we have learned about String class, we explore its constructors and important methods. In this tutorial, we will learn how to create an immutable class in java. First, before creating our own immutable class, we can recall you about what is immutability.

Immutable class means once we create an object we are not allowed to change the content of that object if any person trying to change the content if there is a change in the content with those changes a new object will be created. If there is no change in the content existing object will be reused. Now let's discuss how to create an immutable class in Java. The following rules define a simple strategy for creating an immutable class


How we can create our own immutable class in java?

1. The class must be declared as final so that it can't be extended.
2. Make all the fields final and private.
3. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
4. Use getter method for all the variables in it.
5. Initialize all the fields via using a parameterized constructor.



Example to create an immutable class:


public final class Test{
	//private and final data member.
	private final int i;
	//parameterized constructor.
	Test(int i){
		this.i = i;
	}
	
	/*modify method with return type test.
	because of this modify method test 
	class becomes immutable. */
	public Test modify(int i){
		/*check current objet i value is equal to
		your provided value(passing argument in constructor). 
		if both are same no change in the content 
		therefore we return current object only. */
		if(this.i == i){
			return this;
		}
		/*if there is change in the content, create 
		a new object with updated i value and return
		that object. */
		else{
			return new Test(i);
		}
	}
	public static void main(String args[]){
		Test t1 = new Test(10);
		Test t2 = t1.modify(100);
		Test t3 = t1.modify(10);
		
		System.out.println(t1 == t2); //false
		System.out.println(t1 == t3); //true;
	}
}




How we can create our own immutable class in java? How we can create our own immutable class in java? Reviewed by Prashant Srivastava on January 26, 2020 Rating: 5

No comments:

Powered by Blogger.