18

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.

Frithjof
  • 2,214
  • 1
  • 17
  • 38
  • 4
    I think [this specific answer](http://stackoverflow.com/a/12600683/1743880) answers this question. – Tunaki Nov 01 '15 at 15:20

1 Answers1

19

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 2
    Joshua mentions in the Item 15 : The Java platform libraries contain many immutable classes, including `String`, the boxed primitive classes, and `BigInteger` and `BigDecimal`. But as the class is not marked as `final`, an untrusted client might provide an argument by subclassing the same. Why is he mentioning the class as immutable then? – Farhan stands with Palestine May 01 '19 at 10:08
  • 1
    @FarhanShirgillAnsari You wrote: "Why is he mentioning the class as immutable then?" I *think* he wrote this because all data members are declared as `final`: `private final BigInteger intVal;` and `private final int scale;` – kevinarpe Sep 26 '22 at 02:34