• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

How to create immutable class?

May 8, 2017 By j2eereference Leave a Comment

What is an immutable class: A class whose object’s state cannot be changed or modified once created .Any modification made to immutable class object will produce new object. String is a good example of immutable class as any changes made to String Object will create new String Object.

How to make class immutable:

In order to create an immutable class, we need to follow below points

  • Final class: Declare the class final so that it cannot be inherited by any other class.
  • Private and final member variable: Declaring member variable as private ensures that fields will not be accessible outside the class and declaring them final will ensure that they cannot be change once assigned.
  • Setter Method: Never provide setter method only getter is allowed as setter method will change the state of object.
  • Objects of mutable class (mutable instance variable): If class contains mutable fields then return new object(copy of original object), not the  reference variable to avoid change in object’s state. Example: HashMap or Date class object declared inside a class, as HashMap is a mutable class so any changes  made to its object will not produce new object
  • Constructor: Initialize all field inside constructor and assign all mutable fields using new keyword.

Example to create Immutable class:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.HashMap;
 
final class MyImmutable
{
  private final Integer empId;
  private final String empName;
  private final HashMap<Integer,String> hmap;
 
  public MyImmutable(String ename,Integer empid,HashMap<Integer,String> hmap)
  {
    this.empName=ename;
    this.empId=empid;
    this.hmap=new HashMap<Integer,String>(hmap);
  }
 
public Integer getEmpId()
{
   return empId;
}
 
public String getEmpName()
{
   return empName;
}
 
public HashMap<Integer,String> getMap()
{
   return (HashMap<Integer,String>) hmap.clone();
}
}

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ImmutableDemo
{
  public static void main(String[] args)
  {
    String empName=new String("Shobhna");
    Integer empId=new Integer(749022);
    String address="Sector 21 D,Faridabad";
    HashMap<Integer,String> hmap = new LinkedHashMap<Integer,String>();
    hmap.put(empId,address);
    MyImmutable myImmutable = new MyImmutable(empName, empId, hmap);
    System.out.println(myImmutable.getEmpName());
    System.out.println(myImmutable.getEmpId());
    System.out.println(myImmutable.getMap());
  }
}

Output:

Shobhna
749022
{749022=Sector 21 D,Faridabad}

In the above example ,we are creating immutable class and used all the steps described above to create immutable class. We also used HashMap Object (Mutable class)as an instance variable inside MyImmutable class , any changes made to this mutable object would not produce new HashMap object and make our class as mutable class and not an immutable class .So to make class immutable ,we need to return copy/clone of HashMap object and not reference variable of HashMap. Please refer example and check output .

Benefits of using Immutable class:

  • Immutable class is thread safe, so can be shared by multiple threads in concurrent environment.
  • As immutable class is thread safe so there is no need to use synchronization code and hence less code work for developer
  • Use of immutable object will increase application performance as there is no use of synchronized methods.
  • Immutable objects make good key in HashMap as we will get same key every time when we call hashcode() method.

Related Posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Difference between Stack and Heap memory
  • What is ThreadMXBean in java?
  • What is serialVersionUID
  • What is exchanger in concurrency?

Filed Under: Core Java Tagged With: benefits of immutable class, Immutable class, immutable objects in java, java immutable objects

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.