Immutable Class in Java
In this article, we will explain the immutable class in java. Also, we will see the uses of immutable class. There will be java code examples showing how immutable class can be created in java. An immutable class is a class whose contents cannot be changed.
Following are some important points regarding the immutable class:
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
- Objects of an immutable class are called immutable objects. While dealing with immutable objects, we are not allowed to change an object’s state after its creation. Whenever the state of an object is changed, we get a new object.
- Immutable classes do not provide any methods for changing their content.
- In Immutable classes, only getter methods are available and not setter methods.
- Immutable classes are by default thread-safe in nature.
- Java legacy classes, wrapper classes, String class, are examples of immutable classes in java.
How to Use an Immutable Class in Java?
Before using this class, it is important to know how an immutable class is created. Following are important points to be kept in mind while creating the class:
- An immutable class must be final as it should not be inherited.
- All fields of an immutable class should be made final.
- If any mutable object is used as a field in an immutable class, then special handling has to be implemented so as to prevent its contents from being modified.
- A public constructor should be present.
- Getter methods for all the variables should be defined.
- Setter methods should not be present for any variables.
Following are the main uses of immutable classes in java:
- Simplicity: Since in the case of immutable class, each class is in a single state; therefore, it is a simple design pattern.
- Thread Safe: Another advantage of immutable class comes in the case of a multithreaded environment where no synchronization is required because of the thread-safe nature of the immutable class.
- Robust Design: Writing immutable classes in an application results in robust code.
Apart from the listed advantages, there can be some performance issues when using immutable classes. Hence where thread safety and other features are not important, we can consider using mutable classes for performance improvement.
Examples of Immutable Class in Java
Below are the examples mentioned:
Example #1 – Creating Immutable Class
Now we will see java code examples showing the creation of immutable classes in java. Here is a java code example showing how immutable classes are created in java:
Code:
package com.edubca.immutabledemo; public final class ImmutableDemo { final String studentName; final int rollNumber; public ImmutableDemo (String studentName, int rollNumber) { this.studentName = studentName; this.rollNumber = rollNumber; } public String getStudentName() { return studentName; } public int getRollNumber() { return rollNumber; } public static void main(String[] args) { ImmutableDemo obj = new ImmutableDemo ("John" , 100); // Since no getters are available contents cannot be modified. // Also as variables are declared final they cannot be modified System.out.println("Name is " + obj.getStudentName()); System.out.println("Roll Number is " + obj.getRollNumber()); } }
Output:
The above code shows the creation of an immutable class that does not contain any mutable object as a class member.
Example #2 – Immutable Class Example in Java
Now we will see how to create immutable classes having mutable objects as their members. Some special handling is required In order to maintain immutability in this case.
Problem with a Mutable Object in an Immutable Class:
Here is code example normal showing creation of immutable class having mutable members in it:
Code:
package com.edubca.immutabledemo; import java.util.Date; import java.text.SimpleDateFormat; public final class ImmutableDemo { final String studentName; final int rollNumber; final Date birthDate; public ImmutableDemo (String studentName, int rollNumber, Date birthDate) { this.studentName = studentName; this.rollNumber = rollNumber; this.birthDate=birthDate; } public String getStudentName() { return studentName; } public int getRollNumber() { return rollNumber; } public Date getBirthDate() { return birthDate; } public static void main(String[] args) throws Exception { String birthDate= "31/09/1997"; ImmutableDemo obj = new ImmutableDemo ("John" , 100, new SimpleDateFormat("dd/MM/yyyy").parse(birthDate)); System.out.println("Name is " + obj.getStudentName()); System.out.println("Roll Number is " + obj.getRollNumber()); System.out.println("Birth date is " + obj.getBirthDate()); obj.getBirthDate().setTime(1000); System.out.println("After changing birth date>>>>>>>>>>>>"); System.out.println("Name is " + obj.getStudentName()); System.out.println("Roll Number is " + obj.getRollNumber()); System.out.println("Birth date is " + obj.getBirthDate()); } }
Output:
From the above output, we can see that the contents of the object are changed since the birth date is changed. This breaks the rules of the immutable class.
The Solution to the Problem with a Mutable Object in an Immutable Class:
In order to handle such cases, some changes need to be implemented in the code. In the modified code, when returning mutable objects from the getting method, we do not return the original object; rather, we return the clone of the object. Hence changes to cloned objects do not have any effect on the original object. Here is the modified code:
Code:
package com.edubca.immutabledemo; import java.util.Date; import java.text.SimpleDateFormat; public final class ImmutableDemo { final String studentName; final int rollNumber; final Date birthDate; public ImmutableDemo (String studentName, int rollNumber, Date birthDate) { this.studentName = studentName; this.rollNumber = rollNumber; this.birthDate=birthDate; } public String getStudentName() { return studentName; } public int getRollNumber() { return rollNumber; } public Date getBirthDate() { return (Date)birthDate.clone(); } public static void main(String[] args) throws Exception { String birthDate= "31/09/1997"; ImmutableDemo obj = new ImmutableDemo ("John" , 100, new SimpleDateFormat("dd/MM/yyyy").parse(birthDate)); System.out.println("Name is " + obj.getStudentName()); System.out.println("Roll Number is " + obj.getRollNumber()); System.out.println("Birth date is " + obj.getBirthDate()); obj.getBirthDate().setTime(1000); System.out.println("After changing birth date>>>>>>>>>>>>"); System.out.println("Name is " + obj.getStudentName()); System.out.println("Roll Number is " + obj.getRollNumber()); System.out.println("Birth date is " + obj.getBirthDate()); } }
Output:
From the above output, we can see no change in date value; hence, the class’s immutability remains intact.
Conclusion
From the above discussion, we have a clear understanding of java immutable classes. Also, we have seen the advantages of it.
The above is the detailed content of Immutable Class in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
