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);
}
}