×

How to Create Immutable Classes in Java

Introduction

Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes may be present in a single Java program. While certain classes can be immutable, others can be mutable. A class that cannot have its contents changed is said to be immutable. In simple words if the state of immutable objects instances doesn't change even after initialization, then those classes are called immutable classes in java. For instance, the value of the immutable class String never changes after it has been created.

How is an Immutable Class Created?

Many classes, including String, Boolean, Byte, Short, Integer, Long, Float, Double, etc. are immutable. In essence, the String class and its respective wrapper classes are considered to be immutable.  we can also establish immutable classes by developing final classes with final data members.

To create an immutable class, we need to follow a few steps, and those steps are given below.

Steps

The steps below must be completed to construct an immutable class in Java.

  • Declare the class to be final to prevent extensions. The purpose of making the class final is to avoid inheriting from any other classes. It prevents us from extending a class when we use final with a class.
  • Additionally, the data members must be made final so that they cannot be modified after being initialized with the aid of a constructor 
  • Make all fields private to prevent immediate access. They are inaccessible from outside the class, so the modification of their respective values is undone.
  • The getter and setter methods are used in object-oriented programming to retrieve and set values, respectively. So don’t try to give variables setter methods.
  • By making all mutable data fields final, we ensure to assign values only for one time.
  • Utilize a constructor that performs deep copying to initialize each field. For further understanding as for the getter methods, they return the deep copy of the object rather than the original. This is because if the getter functions return the actual object to anything beyond the class, the class will no longer be immutable.
  • A deep copy should also be used as the first step in the parameterized constructor. This is since, in the absence of a deep copy, an object's data member or property can be changed outside of the class using a reference to the object.

An example for creating immutable classes in Java

In the given program, we can learn about how an immutable class is designed. As mentioned in the above points, all the data fields should be private, and we cannot use mutator methods like the setter method. And, apart from the mutator method, accessor methods should also not be used.

Code

//  Simple Java program on working with immutable class
 
import java . io . * ;
 
public class Employee
{
 public static void main ( String s [ ])
 {
 
   private int age ;
   private String name, location ;
 
// given below is the default constructor with no parameters in employee class
 
public Employee () 
{
 
} 
// given below is overloaded constructor with two parameters in class employee
 
public Employee (String name, int age)
 {
    this . name = name ;
      
    this. age = age ;
 
// Given below is overloaded constructer with three parameters in employee class
 
public Employee ( String name, String location , int age ) 
{
    this ( name ,  age );
    this . location = location ;
}
 
public String getName ( )
{
return name;
}
 
public String getLocation ( )
{
return location;
}
 
public int getAge ( )
{
return age ;
}
 
} // Main
 
} // Employee class

The Importance of Immutable Classes

Immutable classes have several benefits, particularly when used properly in a multi-threaded context. The sole drawback of these classes is that they use more memory than regular classes since each time they are modified, a new object is produced in memory. However, developers shouldn't overestimate this drawback because the benefits these classes offer much outweigh their memory usage.

And finally, an object is said to be immutable if it can only ever provide one state to other objects, regardless of how or when those other objects invoke its methods. If so, it satisfies any definition of thread safety.


Related Topics

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.