为什么String类是final?

Ble*_*eek 7 c# java string final sealed

可能重复:
为什么String最后是Java?

我的编程生活中有各种各样的时刻,我希望String类没有最终/密封/ NotInheritable.

什么是语言建筑师试图阻止我这样做会让一个猴子扳手投入工作.

更确切地说,语言架构师想要通过限制我扩展String类来阻止我投入工作的猴子扳手是什么?

你能列出一个可扩展字符串类的优缺点列表吗?

kro*_*ock 5

String是一个不可变类,这意味着如果在创建它之后无法修改其状态.如果您可以在输入另一个库后修改字符串,或者例如Map,则结果将是不可预测的.

Java API的一个错误是BigInteger并且BigDecimal不是最终的,这意味着当从非受信任的代码接收这些对象时,您需要执行这些对象的防御性副本.相反,您始终可以相信一个String将保持一致.

不值得信赖的BigInteger:

public class DestructiveBigInteger extends BigInteger {

    public DestructiveBigInteger(String value) {
        super(value);
    }

    public BigInteger add(BigInteger val) {
        return BigInteger.ONE; // add() method does not behave correctly
    }

    public BigInteger subtract(BigInteger val) {
        throw new UnsupportedOperationException("subtract is broken");
    }
}
Run Code Online (Sandbox Code Playgroud)

同样的事情是不可能的String.如Effective Java中所述,您需要为这些类型的对象制作防御性副本:

public void setValue(BigInteger value) {
    this.value = new BigInteger(value.toByteArray());
}
Run Code Online (Sandbox Code Playgroud)