The usual way to make a class immutable is to ensure that:
- all fields are private;
- it is impossible to change the fields after construction;
- it is final (so extensions cannot break immutability).
The line is a little special, at least in the Sun / Oracle implementation, since it does not actually perform this procedure. The implementation has a variable field in which it caches the hash code of the object. Therefore, although there is a method that changes the internal state of an object ( hashCode ), this state change does not change the behavior of the object. Any subsequent hashCode calls will work faster, but the result will not be different.
source share