Java中的不可变类

1. 不可变类的特点:

  • 提高程序效率,利用空间换取时间;
  • 安全,线程安全。

2. 不可变类设计:

  • 类的成员变量的声明为 private final;
  • 提供类成员变量的getters方法,不提供setters方法;
  • 为类加上修饰符final关键字,确定其不会被继承;
  • 为类的成员方法加上修饰符final关键字来确保不会被重写。

3. 代码示例:

import java.math.BigInteger;
public class Test {
	public static void main(String[] args) {
		BigInteger fiveThousand = new BigInteger("5000");
		BigInteger fiftyThousand = new BigInteger("50000");
		BigInteger fiveHundredThousand = new BigInteger("500000");
		BigInteger total = BigInteger.ZERO;
		total = total.add(fiveThousand);
		total = total.add(fiftyThousand);
		total = total.add(fiveHundredThousand);
		System.out.println(total);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值