BigDecimal.java 的关键字 "final"

the keyword "final" for BigDecimal.java

众所周知,java中不可变的class应该通过关键字"final"来修饰。但是,为什么 class BigDecimal.java 是一个例外?

why the class BigDecimal.java is an Exception?

不是,final关键字意味着你不能改变bigdecimal的引用,你仍然可以改变对象的值...

final BigDecimal myDec = BigDecimal.valueOf(1L);
System.out.println(myDec);
myDec = myDec.plus(); //invalid, you cant change the ref

这里要考虑的一点是 BigDecimal 是不可变的,因此所有更改对象内容的操作都将 return [=] 的新实例16=]BigDecimal 也是....

没有。编号编号

final 不是 是否意味着您不能通过该引用修改 对象。

当应用于引用时,final 意味着不能更改引用以引用不同的对象。它等同于C++的const限定符。

不变性 意味着没有提供修改对象状态的方法。

也不例外。 BigDecimal本身就是immutable,因为none这个方法确实修改了对象值。 但是您可以更改变量引用。

BigDecimal bd = new Bigdecimal(10);
bd = bd.add(new BigDecimal(50)); // bd new equals 60


如果您将 Bi​​gDecimal 声明为 final,您将无法再更改引用。

final BigDecimal bd = new Bigdecimal(10);
final total = bd.add(new BigDecimal(50)); // Total new equals 60
// bd = bd.add(new BigDecimal(50)); // Will FAIL

Immutable 意味着,class 不包含任何会改变其内部状态的方法。

不可变的示例 class:

class ImmutableInteger {
    private final int value;

    public ImmutableInteger(int value) {this.value = value;}

    public int value() {return value;}

    public ImmutableInteger add(int a) {
        // instead of changing this state, we will create new instance with result
        return new ImmutableInteger(value + a);
    }
}

可变的例子 class:

class MutableInteger {
    private int value;

    public MutableInteger(int value) {this.value = value;}

    public int value() {return value;}

    public MutableInteger add(int a) {
        value += a; // mutating internal state
        return this;
    }
}

Modifier final 表示该变量不能更改。对于 object type 的变量,这意味着该变量不能引用其他对象。对于原始类型的变量(byte、short、int、long、float、double),这意味着该值不能更改。

BigDecimal a = new BigDecimal(1);
BigDecimal b = a.add(new BigDecimal(1)); // returns result in new instance (a is not changed = immutable)
a = new BigDecimal(5); // ok, 'a' is not final = can be change to refer to other BigDecimal instance)

final BigDecimal b = new BigDecimal(1);
BigDecimal c = b.add(new BigDecimal(2)); // // returns result in new instance (a is not changed = immutable)
b = new BigDecimal(5); // NOT OK!!!, 'b' is final = can not be changed to refer to other object