Uncategorized

How to create immutable object in Java

How to create immutable objects, In this article we will see why do we need immutable objects in java, and how to create immutable objects in java. immutability offers a lot of benefit it allows to share object between multiple thread in java

Mandu

without any synchronization and without fear of any state curruption because immutable object can not change there state once created.

Immutable objects are essential for concurrent program String in java is immutable and wrapper classes are also immutable , immutable objects are good keys in java hashmap and they can be shared between multiple thread without using synchronization in java. here are some of steps to make a class immutable in java:

To create a class immutable, you need to follow following steps:

  1. you need to declare the class as final so it can’t be extended.2.you have to Make all fields private so that direct access is not allowed.3.Please Don’t provide setter methods for variables
  2. makes sure that all mutable fields final so that it’s value can be assigned only once.
  3. don’t forget to Initialize all the fields via a constructor performing deep copy.6.don’t forget to perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

I hope you like this immutable object tutorial stay tuned for more java tips.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s