An immutable class is simply a class whose instances can not be modified, all of the information contained in each instance is provided when it is created and is fixed for the lifetime of object.
There are many good reasons for this: Immutable classes are easier to design, implement and use than mutable classes. They are less prone to error and are more secure.
To make class immutable:
- Don't provide any methods that modify the object's state
- Ensure that theclass can't be extended.
- Make all fields final.
- Make all fields private.
- Immutable objects are simple, an immutable object can be in exactly one state, the state in which it was created.
- Immutable ojects are inherently thread-safe; they require no synchronization
- Immutable ojects can be shared freely. One easy way to do this is to rpvoide public static final constants for frequently used values, for example
To summarize, resist the urge to write a setter method for every getter method. Classes should be immutable unless there's a very good reason to make them mutable.public static final Complex ZERO = new Complex(0, 0);public static final Complex ONE = new Complex(1, 0);public static final Complex I = new Complex(0, 1);