Search code examples
javakeywordfinalbigdecimal

the keyword "final" for BigDecimal.java


as everyone knows, the immutable class in java should be modified by the keyword "final". But, why the class BigDecimal.java is an Exception?


Solution

  • Immutable means, that class does not contain any method that would change it's internal state.

    Example of immutable class:

    class ImmutableInteger {
        private final int value;
    
        public ImmutableInteger(int value) {this.value = value;}
    
        public int value() {return value;}
    
        public ImmutableInteger add(int a) {
            // instead of changing this state, we will create new instance with result
            return new ImmutableInteger(value + a);
        }
    }
    

    Example of mutable class:

    class MutableInteger {
        private int value;
    
        public MutableInteger(int value) {this.value = value;}
    
        public int value() {return value;}
    
        public MutableInteger add(int a) {
            value += a; // mutating internal state
            return this;
        }
    }
    

    Modifier final means, that variable can not be changed. For variable of object type it means, that variable can not refer to other object. For variable of primitive type (byte, short, int, long, float, double) it means, that value can not be changed.

    BigDecimal a = new BigDecimal(1);
    BigDecimal b = a.add(new BigDecimal(1)); // returns result in new instance (a is not changed = immutable)
    a = new BigDecimal(5); // ok, 'a' is not final = can be change to refer to other BigDecimal instance)
    
    final BigDecimal b = new BigDecimal(1);
    BigDecimal c = b.add(new BigDecimal(2)); // // returns result in new instance (a is not changed = immutable)
    b = new BigDecimal(5); // NOT OK!!!, 'b' is final = can not be changed to refer to other object