How To Create Immutable Class In Java?

Declare the class as `final`

Make all fields `private` and `final`

Initialize all fields through a constructor

Do not provide setter methods

If a field is mutable, create defensive copies in the constructor

If a getter returns a mutable object, return a defensive copy

Use immutable types for fields whenever possible

Do not allow subclassing that can alter behavior

Ensure the class state is fully initialized before use

Avoid exposing internal mutable references

Keep all methods side-effect free

Suggested for You

Trending Today