01 logo

Create An Immutable Class In Java

Learn about how to create an Immutable class in java and its benefits.

By Rakshit ShahPublished 3 years ago 5 min read
1
Immutable class cover image | Image by Author Rakshit Shah

Table of Contents

  1. Overview
  2. Usage of Immutable class
  3. Steps to create an Immutable class
  4. Exploring Existing Immutable classes in Java
  5. Examples with/without Mutable/Immutable class
  6. Conclusion

1. Overview

Immutable class, once an object is instantiated, we cannot modify its content. In Java, all the wrapper classes (let’s say, Integer, Short, Boolean, Byte, etc.) and String, etc. classes — are immutable. We can create our own immutable class as well.

An object is immutable if its state cannot be modified after construction. Immutable objects don’t expose any way for other objects to modify their state; the object’s fields are initialized only once inside the constructor and never change again.[³]

Always remember that,

  • Primitive data types — includes byte, short, int, long, float, double, boolean, and char.
  • Non-primitive data types — such as String, Arrays, Interfaces, and Classes.

In this article, we will explain point-to-point the typical steps to create an Immutable class with examples and their usages.

2. Usage of Immutable class

As per the current trend, In all IT industries, every software application must have to be distributed and multi-threaded. I know most of the developers are afraid of implementing Threads in their applications.

When it comes to multi-threaded applications, it always causes headaches for software engineers since they are required to protect the state of their objects from concurrent modifications of several threads at the same time. Hence, the developers normally use the Synchronized blocks whenever they modify the state of an object.

What you can do with immutable classes?

  • States are never modified
  • Every modification of state results in a new instance, hence each thread would use a different instance and developers wouldn’t worry about concurrent modifications.

3. Steps to create an Immutable Class

  1. The class must be declared as final (Final class cannot be inherited)
  2. Data members in the class must be declared as private (It will avoid direct access)
  3. Data members in the class must be declared as final (Nobody can change the value of it on object instantiation or creation.)
  4. A parameterized constructor should initialize all the fields performing a deep copy (So that data members can’t be modified with object reference)
  5. Deep Copy of objects should be performed in the getter methods (To return a copy rather than returning the actual object reference)
  6. No setters, Don’t add any setter methods (To not have the option to change the value of the instance variable)
  7. When exposing methods that modify the state of the class, you must always return a new instance of the class.

If the class holds a mutable object(s):

  • Inside the constructor, make sure to use a clone copy of the passed argument and never set your mutable field to the real instance passed through the constructor, this is to prevent the clients who pass the object from modifying it afterward.
  • Make sure to always return a clone copy of the field and never return the real object instance as mentioned in Step 7.

4. Exploring Existing Immutable classes in Java

You always heard about the well-known immutable class String. Once initialized its value cannot be modified. Operations like trim, substring, replace always return a new instance and don’t affect the current instance, that’s why we usually call trim like the following,

String and float addition operation | Image by Author

After calling x+= 5.5, a new instance is created holding the value: 7, and the first instance is lost.

5. Examples with or without Mutable or Immutable class

Let’s go with simple and easy examples first.

1. Simple Immutable Class

ImmutableEmployee class java | Image by Author

From the above class, it doesn’t hold any mutable object and never exposes its fields in any way as they are final and private. These types of classes are normally used for caching purposes.

2. Passing Mutable Objects to Immutable Class

We create a mutable class called Age and add it as a field to ImmutableEmployee:

Age.java

Age.java class | Image by Author

ImmutableEmployee.java

ImmutableEmployee java | Image by Author

If you call the main method and check whether your class ImmutableEmployee is immutable or not?

Main method to run | image by Author

Output:

Rax age year before modification = 1994

Rax age year after modification = 1995

Understand what just happened? — Let me elaborate!

We claim that ImmutableEmployee is an immutable class whose state is never modified after construction, however in the above example we are able to modify the age of Rax even after constructing Rax object. If you check the implementation of the above ImmutableEmployee constructor, you will see that the age field is being assigned to the instance of the Age argument, so whenever the referenced Age is modified outside the class, the change is reflected directly on the state of Rax instantly. Check out Pass by value OR pass by reference concept to more deeply understand this concept.

How you can fix such a situation?

As said above, in step 8 to create Immutable objects, clone instance will handle everything for you.

ImmutableEmployee Method Implementation | Image by Author

Output:

Rax age year before modification = 1994

Rax age year after modification = 1994

But, It is not the perfect Immutable class yet! Check the below example about how you can make it a perfect Immutable class.

3. Returning Mutable Objects From Immutable Class

As per step 7, when returning mutable fields from the immutable object(s), you should return a clone instance of them and not the real instance of the field.

In order to modify getAge Method in order to return a clone of the object’s age:

getAge Method | Image by Author

It will return you perfect output for your Immutable class.

Rax age year before modification = 1994

Rax age year after modification = 1994

6. Conclusion

Finally, an object is immutable if it can present only one state to the other objects, no matter how and when they call its methods. If so it’s thread-safe by any definition of thread-safe.

Advantages:

  • It gives benefit for multi-threaded environment

Disadvantages:

  • Memory Consumption is more because on each modification of them a new object is created in the memory.

Reference:

  • [1] Java™: The Complete Reference Herbert Schildt,
  • [2] Java First Head Book,
  • [3] DZone

Get my stories in your feeds by subscribing to me, or become a vocal+ member to read all stories of thousands of other writers, participate in all challenges and get a payout with low fees and less payout threshold on Vocal Media.

© Originally published at BeingCoders » Immutable Class, also republished on Medium by Rakshit Shah.

how to
1

About the Creator

Rakshit Shah

I am Computer Engineer and love to make websites and software. I am really eager to know about anything. I am curious to read and write cool stuff.

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2024 Creatd, Inc. All Rights Reserved.