×

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

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 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.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.