How to write an immutable Class?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值