为什么Java的BigDecimal类没有声明为final? [英] Why is Java's BigDecimal class not declared as final?

查看:499
本文介绍了为什么Java的BigDecimal类没有声明为final?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查Java的 BigDecimal 类的源代码时,令我惊讶的是它被声明为final class:

While checking the source code of Java's BigDecimal class, I was surprised that it was not declared as a final class:

BigDecimal类

public class BigDecimal
extends Number
implements Comparable<BigDecimal>

不可变,任意精度的带符号十进制数字.

Immutable, arbitrary-precision signed decimal numbers.

(来自 Oracle文档)

是否有特定原因,或者开发人员只是忘记添加该关键字?最好不要将不可变的类声明为final?

BigInteger 也是一样,但不适用于 BigInteger 声明为最终版本的 String .

推荐答案

https://blogs.oracle.com引用/darcy/entry/compatfully_evolving_bigdecimal :

但是,由于BigDecimal不是最终的并且具有公共构造函数,因此这里可能存在复杂性,因此可以将其子类化. (如《有效Java,第13项,有利的不变性》所述,这是编写类时的设计疏忽.)

(重点是我的).

由于Java一直都向后兼容,因此将其最终定型是毫无疑问的:它将破坏现有的子类.

Since Java has always favored backward compatibility, making it final now is out of question: it would break existing subclasses.

也就是说,就像使用Date一样,我只是假设没有人继承BigDecimal,因此应该将BigDecimal当作真正不可变的来使用.

That said, just as when using Date, I would simply assume that no-one ever subclasses BigDecimal, and that BigDecimal should thus be used as if it were truly immutable.

这篇关于为什么Java的BigDecimal类没有声明为final?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆