What is immutable class: A class is immutable if no method of the class can mutate its objects. For example, the String
class is immutable. An immutable object cannot be modified once it is constructed. The information contained in immutable object is provided at the time of object creation and it is fixed for the lifetime of the object. If you need to modify the object, you can always create a new one that contains the modifications, but the existing won't change. Because immutable objects cannot be modified, therefore, they are thread-safe and all threads will see the same consistent state of the object. There are examples of immutable built-in Java classes such as the primitive wrapper classes (Byte
, Short
, Integer
, Long
, Float
, Double
, Character
, and Boolean
), and BigInteger
and BigDecimal
.
Rules to create immutable class: In order to make a Java class immutable, follow these rules.
private
and final
. private
, so that they cannot be accessed outside the class; and final
, so that they cannot be changed after construction.final
. This ensures that the class can't be extended. If the class is not marked final
, it might be possible for someone to extend the class and mutate its members.Advantages of immutable objects: An immutable object remains in exactly one state, the state in which it was created. Therefore, immutable object is thread-safe. They cannot be corrupted by multiple threads accessing them concurrently. This is far and away the easiest approach to achieving thread safety.
Disadvantages of immutable objects: Creating an immutable class seems at first to provide an elegant solution. However, whenever you do need a modified object of that new type you must suffer the overhead of a new object creation, as well as potentially causing more frequent garbage collections. The only real disadvantage of immutable classes is that they require a separate object for each distinct value. Creating these objects can be costly, especially if they are large.
For reader's reference, the following piece of Java code demonstrates an immutable class ImmutablePerson
.
/* ImmutablePerson.java */ //immutable class is declared final public final class ImmutablePerson { //fields are made private and final to restrict outside access private final String fname; private final String lname; private final int age; public ImmutablePerson(String fname, String lname, int age) { this.fname = fname; this.lname = lname; this.age = age; } //provide getters, no mutators public String getFname() { return this.fname; } public String getLname() { return this.lname; } public int getAge() { return this.age; } }
Hope you have enjoyed reading about creating immutable classes and objects in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!
Share this page on WhatsApp