How to create immutable class in java?
The key points for immutable are:
- no setters methods
- make variables private and final
- return lists using Collections.unmodifiableList - never return any mutable field; always return either a copy (deep if appropriate) or an immutable version of the field
- make class final
- if variables are changed internally in the class this change is not visible and has no effect outside of the class (including affecting things like
equals()
andhashcode()
).
Resource Link:
No comments:
Post a Comment