InterviewSolution
Saved Bookmarks
| 1. |
Create Immutable class in Java |
|
Answer» An immutable class in Java is one that cannot change its state after its construction. Some of the requirements to create an immutable class in Java are GIVEN as FOLLOWS:
An example that demonstrates the creation of an immutable class in Java is given as follows: public final class Employee { final int empNum; final String name; final int salary; public Employee(int empNum, String name, int salary) { this.empNum = empNum; this.name = name; this.salary = salary; } public int empNumReturn() { return empNum; } public String nameReturn() { return name; } public int salaryReturn() { return salary; } }The class given above is a basic immutable class. This class does not contain any mutable object or any setter methods. This type of a basic class is normally used for caching purposes. |
|