immutable class should be final?

The explanation for this is given in the book ‘Effective Java’

Consider BigDecimal and BigInteger classes in Java .

It was not widely understood that immutable classes had to be effectively final
when BigInteger and BigDecimal were written, so all of their methods may be
overridden. Unfortunately, this could not be corrected after the fact while preserving backward compatibility.

If you write a class whose security depends on the immutability of a BigInteger or BigDecimal argument from an un-trusted client, you must check to see that the argument is a “real” BigInteger or BigDecimal, rather than an instance of an un trusted subclass. If it is the latter, you must defensively copy it under the assumption that it might be mutable.

   public static BigInteger safeInstance(BigInteger val) {

   if (val.getClass() != BigInteger.class)

    return new BigInteger(val.toByteArray());


       return val;

   }

If you allow sub classing, it might break the “purity” of the immutable object.

Leave a Comment