immutable class should be final?

后端 未结 6 715
温柔的废话
温柔的废话 2020-11-29 09:15

It says in this article that:

Making a class final because it is immutable is a good reason to do so.

I\'m a bit puzzled by thi

6条回答
  •  误落风尘
    2020-11-29 09:45

    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.

提交回复
热议问题