Question: How do you create an immutable class?
Answer: Immutable class or objects are those whose state(object's data) cannot be changed once
they are created. For example String class is an immutable class. Now the question is how
to create immutable objects. Below are the steps for creating immutable objects.
- Make all the fields i.e, all the member variables and methods as final.
- To further restrict the access we can use a private access modifier.
- Now mark the class as final. If class is declared as final then no other class can extend it.
Below is an example for immutable class.
package com.ram; final class Immutable{ private final int empId; private final String empName; Immutable(int empId, String empName){ this.empId = empId; this.empName = empName; } public int getEmpId() { return empId; } public String getEmpName() { return empName; } } public class ImmutableClassExample { public static void main(String[] args) { Immutable imuObj = new Immutable(123456, "Ram"); System.out.println("Employye Id = "+imuObj.getEmpId()); System.out.println("Employee Name = "+imuObj.getEmpName()); } }
Now the a question arises. What is the use of immutable class?
- Immutable classes are thread safe (it may be used from multiple threads at the same time without causing problems).
- They do not have any synchronization issues.
- Immutable objects do not copy constructors (A copy constructor is a Constructor that references to another object in the same class).
- Immutable objects can be reused by caching them.
No comments:
Post a Comment