Why String and wrapper classes are immutable and final in java

Introduction:

Immutable objects are, objects whose state (data) cannot change after construction. String and Wrapper classes in java are immutable. (refer this link for more details)

Immutable objects simplify the program based on below:

  1. They are simple to construct, test and use.
  2. They are automatically thread-safe and won't face synchronization issues.
  3. They don't need a copy constructor or implementation of clone() and no need to copied defensively when used as fields.
  4. They allow hashCode() to use lazy initialization, and to cache its return value.
  5. Can be utilized as keys for Map or Set elements (won't change state while in collection).

How to create immutable object in java:

  1. Make sure that class cannot be overridden, by making class final or by using static factories and keep constructors private.
  2. Make sure fields are private and final.
  3. Make sure that values for fields are set through constructor only. (No setters)
img logo

No comments :

Post a Comment