为什么 Java 的 BigDecimal class 没有声明为最终的?
Why is Java's BigDecimal class not declared as final?
在检查 Java 的 BigDecimal
class 的源代码时,令我惊讶的是 没有 声明为 final class
:
Class BigDecimal
public class BigDecimal
extends Number
implements Comparable<BigDecimal>
Immutable, arbitrary-precision signed decimal numbers.
(来自Oracle Docs)
这是否有特定原因,或者开发人员只是忘记添加该关键字?不将不可变 classes 声明为 final 是一种好习惯吗?
声明为final的BigInteger
, but not for String
也是如此。
引自https://blogs.oracle.com/darcy/entry/compatibly_evolving_bigdecimal:
However, there is a possible complication here since BigDecimal is not final and since it has public constructors, it can be subclassed. (As discussed in Effective Java, Item 13, Favor Immutability, this was a design oversight when the class was written.)
(强调我的)。
由于 Java 一直支持向后兼容性,现在将其定为 final 是毫无疑问的:它会破坏现有的子类。
就是说,就像使用 Date 时一样,我会简单地假设没有人将 BigDecimal 子类化,因此应该将 BigDecimal 当作真正不可变的来使用。
在检查 Java 的 BigDecimal
class 的源代码时,令我惊讶的是 没有 声明为 final class
:
Class BigDecimal
public class BigDecimal extends Number implements Comparable<BigDecimal>
Immutable, arbitrary-precision signed decimal numbers.
(来自Oracle Docs)
这是否有特定原因,或者开发人员只是忘记添加该关键字?不将不可变 classes 声明为 final 是一种好习惯吗?
声明为final的BigInteger
, but not for String
也是如此。
引自https://blogs.oracle.com/darcy/entry/compatibly_evolving_bigdecimal:
However, there is a possible complication here since BigDecimal is not final and since it has public constructors, it can be subclassed. (As discussed in Effective Java, Item 13, Favor Immutability, this was a design oversight when the class was written.)
(强调我的)。
由于 Java 一直支持向后兼容性,现在将其定为 final 是毫无疑问的:它会破坏现有的子类。
就是说,就像使用 Date 时一样,我会简单地假设没有人将 BigDecimal 子类化,因此应该将 BigDecimal 当作真正不可变的来使用。