什么是不可变对象(immutable object)?Java 中怎么创建一个不可变对象?

一、概念

不可变对象指对象一旦被创建,状态就不能再改变。任何修改都会创建一个新的对象,如 String、Integer及其它包装类。详情参见答案,一步一步指导你在 Java 中创建一个不可变的类。


二、创建不可变类的规则如下:

1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Object must be properly constructed i.e. object reference must not leak during construction process.
4. Object should be final in order to restrict sub-class for altering immutability of parent class.


三、例:
public final class Contacts {

	private final String name;
	private final String mobile;
	
	public Contacts(String name, String mobile) {
		this.name = name;
		this.mobile = mobile;
	}

	public String getName() {
		return name;
	}

	public String getMobile() {
		return mobile;
	}
}

public final class ImmutableReminder {

	private final Date remindingDate;
	
	public ImmutableReminder(Date remindingDate) {
		if (remindingDate.getTime() < System.currentTimeMillis()) {
			throw new IllegalArgumentException("Can not set reminder for past time: " + remindingDate);
		}
		this.remindingDate = new Date(remindingDate.getTime());
	}

	public Date getRemindingDate() {
		return (Date) remindingDate.clone();
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值