Here are the steps to create immutable class:
Declare the class as final, we can not extend the final class.
public final class MyTestImmutable { ... }
Declare all fields as final. Final fields can not be changed once its assigned.
private final int salary;
Do not provide any method which can change the state of the object, for example the setter methods which changes the values of the instance
variables.
The “this” reference is not allowed to escape during construction from the immutable class and the immutable class should have exclusive
access to fields that contain references to mutable objects like arrays, collections and mutable classes like Date etc by:
Declaring the mutable references as private.
Not returning or exposing the mutable references to the caller.
|