现在的位置: 首页 > 综合 > 正文

How to write an immutable Class?

2018年05月24日 ⁄ 综合 ⁄ 共 1510字 ⁄ 字号 评论关闭
package com.test.ImmutableClass;

public final class MyImmutable2 {
	private final int[] myArray;

	public MyImmutable2(int[] anArray) {
		this.myArray = anArray; // wrong
	}

	public String toString() {
		StringBuffer sb = new StringBuffer("Numbers are: ");
		for (int i = 0; i < myArray.length; i++) {
			sb.append(myArray[i] + " ");
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		int[] array = { 1, 2 };
		MyImmutable2 myImmutableRef = new MyImmutable2(array);
		System.out.println("Before constructing " + myImmutableRef);
		array[1] = 5; // change (i.e. mutate) the element  
		System.out.println("After constructing " + myImmutableRef);
	}

}

//Out put:  
//	Before constructing Numbers are: 1 2  
//	After constructing Numbers are: 1 5  

Immutable objects are instances whose state doesn’t change
after it has been initialized. For example, String is an immutable class and once instantiated its value never changes.

ReadWhy
String in immutable in Java

Immutable objects are good for caching purpose because you don’t need to worry about the value changes. Other benefit of immutable class is that it is inherently thread-safe,
so you don’t need to worry about thread safety in case of multi-threaded environment.

Here I am providing a way to create immutable class via an example for better understanding.

To create a class immutable, you need to follow following steps:

  1. Declare the class as final so it can’t be extended.
  2. Make all fields private so that direct access is not allowed.
  3. Don’t provide setter methods for variables
  4. Make all mutable fields final so that it’s value can
    be assigned only once.
  5. Initialize all the fields via a constructor performing deep copy.
  6. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

抱歉!评论已关闭.