Java Immutable Class
In Java, when we create an object of an immutable class, we cannot change its value. For example, String is an immutable class. Hence, we cannot change the content of a string once created.
Besides, we can also create our own custom immutable classes. Here's what we need to do to create an immutable class.
- declare the class as
finalso it cannot be extended - all class members should be
privateso they cannot be accessed outside of class - shouldn't contain any setter methods to change the value of class members
- the getter method should return the copy of class members
- class members are only initialized using constructor
Example: Java program to create immutable class
Output
Name: nodmek Date: 2011
In the above example, we have created an immutable class named Immutable.