How to create an immutable class in Java?

How to create an immutable class in java

Following steps are required to create an immutable class in java.

Step 1 : Declare the class as final so that no other class it can’t be extended.
Step 2 : Make all the fields private so that direct access is not allowed.
Step 3 : Make all the fields final so that value once assigned can not be changed.
Step 4 : Don’t create setters, use constructor to initialize the variables.
Step 5 : For mutable objects return a copy rather than returning the actual object reference.

Java Professional with rich experience in Java development.
– Designing and developing high-volume, low-latency applications with high-availability and performance.
– Writing well designed, robust and efficient code.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By :