Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 446
Frithjof Avatar asked Nov 01 '15 15:11

Frithjof


People also ask

What is the default value for BigDecimal in Java?

Assigned Tags. If you are using type BigDecimal, then its default value is null (it is object, not primitive type), so you get [1] automatically.

Is BigDecimal a wrapper class in Java?

Introduction. Java includes a BigDecimal class for performing high-precision arithmetic which can be used in banking or financial domain based application. This class approximately fit into the same category as the “wrapper” classes but has some very useful methods.

Is BigDecimal immutable in Java?

Since BigDecimal is immutable, these operations do not modify the existing objects. Rather, they return new objects.

What can I use instead of BigDecimal?

If you need to use division in your arithmetic, you need to use double instead of BigDecimal.


1 Answers

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.

like image 130
JB Nizet Avatar answered Sep 18 '22 13:09

JB Nizet