How to make a java class immutable

1. What are the benefits of immutable classes

  1. are simple to construct, test, and use
  2. are automatically thread-safe and have no synchronization issues
  3. do not need a copy constructor
  4. do not need an implementation of clone
  5. allow hashCode to use lazy initialization, and to cache its return value
  6. do not need to be copied defensively when used as a field
  7. make good Map keys and Set elements (these objects must not change state while in the collection)
  8. have their class invariant established once upon construction, and it never needs to be checked again
  9. always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state

How to make a class immutable

Java documentation itself has some guidelines identified in this link. We will understand what they mean actually:

1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.

This principle says that for all mutable properties in your class, do not provide setter methods. Setter methods are meant to change the state of object and this is what we want to prevent here.

2) Make all fields final and private

This is another way to increase immutability. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.

3) Don’t allow subclasses to override methods

The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.

4) Special attention when having mutable instance variables


Quoted from: https://howtodoinjava.com/core-java/basics/how-to-make-a-java-class-immutable/


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325873846&siteId=291194637