Search code examples
javaimmutabilityfinal

java : Question regarding immutable and final


I am reading the book Effective Java.

In an item Minimize Mutability , Joshua Bloch talks about making a class immutable.

  1. Don’t provide any methods that modify the object’s state -- this is fine.

  2. Ensure that the class can’t be extended. - Do we really need to do this?

  3. Make all fields final - Do we really need to do this?

For example let's assume I have an immutable class,

class A{
private int a;

public A(int a){
    this.a =a ;
}

public int getA(){
    return a;
}
}

How can a class which extends from A , compromise A's immutability ?


Solution

  • Like this:

    public class B extends A {
        private int b;
    
        public B() {
            super(0);
        }
    
        @Override
        public int getA() {
            return b++;
        }
    }
    

    Technically, you're not modifying the fields inherited from A, but in an immutable object, repeated invocations of the same getter are of course expected to produce the same number, which is not the case here.

    Of course, if you stick to rule #1, you're not allowed to create this override. However, you cannot be certain that other people will obey that rule. If one of your methods takes an A as a parameter and calls getA() on it, someone else may create the class B as above and pass an instance of it to your method; then, your method will, without knowing it, modify the object.