Search code examples
javaimmutability

Do final fields really prevent mutability in Java?


From the famous book Java Concurrency in Practice chapter 3.4.1 Final fields

Just as it is a good practice to make all fields private unless they need greater visibility[EJ Item 12] , it is a good practice to make all fields final unless they need to be mutable.

My understanding of final references in Java : A final reference/ field just prevents the field from getting reinitialized but if it references a mutable object, we can still change its state rendering it mutable. So I am having difficulty understanding the above quote . What do you think ?


Solution

  • Final fields prevent you from changing the field itself (by making it "point" to some other instance), but if the field is a reference to a mutable object, nothing will stop you from doing this:

    public void someFunction (final Person p) {
        p = new Person("mickey","mouse"); //cant do this - its final
        p.setFirstName("donald");
        p.setLastName("duck");
    }
    

    The reference p above is immutable, but the actual Person pointed to by the reference is mutable. You can, of course, make class Person an immutable class, like so:

    public class Person {
        private final String firstName;
        private final String lastName;
        public Person(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
        //getters and other methods here
    }
    

    Such classes once created, cannot be modified in any way.