Home » Core Java » How to create an Immutable class

How to create an Immutable class

How to create an Immutable class ? This is a very important core Java interview question in an interview room.I will try to explain it to the point and precise.

Immutable class means once you create the class you can not change its content.String is an immutable class and once it is instantiated its value can not be changed.Any change in value of a String results in a new String.

In order to create immutable class in java, you need to do the following.

1. Declare the class as final,so that it can not be extended.
2. Declare all fields as private so that no other class can access it.
3. Do not provide setter methods for any variable so that no one can set and change the value of any variable
4. If there is any mutable field then make it as final and return clone of this object in the getter method.
5. Provide only one constructor and assign the final values inside constructor.Make sure you perform deep cloning for mutable object.

 

Program ::

Output ::


Leave a comment

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

eleven − 4 =