Friday 26 May 2023

How to create Immutable class in Java?Example

In Java, an immutable class is a class whose instances cannot be modified after they are created. Once an object of an immutable class is instantiated, its state (data) cannot be changed. This means that the object's fields, once assigned, remain constant throughout its lifetime.

Immutable classes are designed to ensure immutability, which brings several benefits:

1. Thread Safety: Immutable objects are inherently thread-safe because they cannot be modified once created. This eliminates the need for synchronization or locking mechanisms when dealing with shared data in a concurrent environment.

2. Simplicity and Predictability: Immutable objects have a simple and predictable state. Once created, their state cannot be altered by any internal or external factors, leading to more reliable and bug-free code.

3. Security: Immutable objects are useful in security-related scenarios. For example, in cryptographic algorithms, using immutable objects prevents data tampering or modification, ensuring the integrity of sensitive information.

4. Caching: Immutable objects are often used for caching purposes since their values cannot change. Once computed or initialized, the object can be safely cached and reused without worrying about its state being modified.

To create an immutable class, follow the guidelines mentioned earlier: declare the class as final, make all fields private and final, provide a constructor to initialize the fields, avoid setter methods, and provide only getter methods.

To create an immutable class in Java, you need to follow these guidelines:

1. Declare the class as final: By declaring the class as final, you prevent any inheritance, ensuring that the class cannot be subclassed and its behavior cannot be modified.

2. Declare all fields as private and final: This ensures that the fields cannot be accessed or modified directly after the object is instantiated. Making the fields final ensures that their values cannot be changed once assigned.

3. Do not provide any setter methods: Since the class is immutable, there should be no methods that modify the internal state of the object. Therefore, omit setter methods for the class fields.

4. Initialize the fields in the constructor: Provide a constructor to initialize all the fields of the class. Assign the values of the constructor parameters to the corresponding fields.

5. Avoid exposing mutable objects: If your immutable class contains fields that refer to mutable objects (e.g., collections), make sure that these objects are not directly accessible or modifiable from outside the class. This can be achieved by returning defensive copies of these objects or making them read-only.

6. Provide only getter methods: To access the values of the class fields, provide getter methods that return the field values. Ensure that the getter methods do not expose any internal references to mutable objects.Here's an example of an immutable class representing a person:

java
public final class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }


In the above example, the Person class is declared as final, and the fields name and age are marked as private and final. The constructor initializes these fields, and getter methods are provided to access their values. Since the fields are final, they cannot be modified after object creation, making the Person class immutable.

To observe the behavior of an immutable class, you can create instances of the class and access its fields using the getter methods. Here's an example of how you can use the Person class from the previous code snippet:

java
public class Main { public static void main(String[] args) { Person person = new Person("John Doe", 30); String name = person.getName(); int age = person.getAge(); System.out.println("Name: " + name); System.out.println("Age: " + age); } }
When you run the Main class, it will output:

output
Name: John Doe Age: 30

This way you can access the fields of an immutable object and retrieve their values, but you cannot modify the object's state after it is created.

By following these steps, you can create immutable classes in Java that ensure the objects' state cannot be changed after creation, leading to more predictable and thread-safe code.

No comments:

Post a Comment

Seven front-end development trends in 2023-2024

With the increasing prevalence of apps in the digital landscape , the role of front-end developers remains essential. While apps aim to ove...

Popular Posts