Why is Java's BigDecimal class not declared as final?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 16:43:13

问题


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

Class BigDecimal

public class BigDecimal
extends Number
implements Comparable<BigDecimal>

Immutable, arbitrary-precision signed decimal numbers.

(from the Oracle Docs)

Is there a specific reason for this or did the developers just forget to add that keyword? Is it a good practice to not declare immutable classes as final?

The same goes for BigInteger, but not for String which is declared as final.


回答1:


Quote from 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.)

(emphasis mine).

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

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.



来源:https://stackoverflow.com/questions/33463729/why-is-javas-bigdecimal-class-not-declared-as-final

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!