Follow these steps to implement an immutable class:
- Mark the class as final. It should not be extended by another class.
- All the attributes must be final and private. You can assign a value to an attribute only once.
- Don't provide methods that can assign a value to an attribute. Attributes must be initialized in the constructor of the class.
- If any field value object is mutable (for example, java.util.Date), always return a defensive copy in the getter field.
- Don't leak the this reference from the immutable class constructor (for example, the following code that leaks the this reference before the constructor is complete):
public final NotSoImmutable implements Listener { private final int x; public NotSoImmutable(int ...