Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Sunday, 18 May 2014

How to make a class Immutable in Java - Example & Explanation

What is immutable class in Java? And How to make a class immutable in java? Are two very popular and hot topics as if today. In this particular blog we will look into these two in details and will try to understand benefits if immutable classes in context of Java Language.


What is Immutable class in Java ?

In Java an immutable class is a class whose object’s state can not be changes once created, or any modification on immutable object’s results in another immutable object. Even JDK itself contains a number of immutable classes like String, Float and other wrapper classes. To understand immutable class clearly we can take a simple example of String and StringBuffer classes, any modification on String object i.e. substring, concat ..etc results in a new immutable object while operations performed on StringBuffer class does not create a new object instead modifications are refleted on exiting object only.


How to make a class immutable in Java ?

Let us now discuss how to make a class immutable, there are a number of ways to get an immutable class. Even Java Documentation points out certain guidelines on the same, which we will follow here to get an immutable class.

1) Never provide a setter method for the class, setter methods are used to change the state of a class’s members. This is what we want to prevent here.

2) Make all fields private and final, this will make them non accesable outside the class and their values can not be changed because of being final.

3) Make the class final, so that the class can not be subclassed. This will prevent the class’s methods from overriden.

4) Special attention needs to be applied with mutable reference variables, with reference variables even final can not prevent their value to be changed. The simplest way to prevent reference variables’s vales is to not provide actual object and provide a copy of them.

5) Make the default constructor of the class private and provide instances with a factory method.

package com.beingjavaguys.com;

import java.util.Date;

/**
 * @Author Nagesh Chauhan
 */
/* Making class final, prevents it's methods from overriden in subclasses */
public final class IAmImmutable {

 private Integer id;
 private String name;
 private Date currentDate;

 /*
  * private constructor ensured no unwanted object creation
  */
 private IAmImmutable(Integer id, String name, Date currentDate) {
  this.id = id;
  this.name = name;
  this.currentDate = currentDate;
 }

 /* this hold the logic of object creation, only point to get an object */
 static IAmImmutable getInstance(Integer fld1, String fld2, Date fld3) {
  return new IAmImmutable(fld1, fld2, fld3);
 }

 /* Integer is a immutable class, this can be served directly */
 public Integer getId() {
  return id;
 }

 /* String is a immutable class, this can be served directly */
 public String getName() {
  return name;
 }

 /*
  * Date class is mutable so we don't provide an direct object, instead we
  * provide a copy of it
  */
 public Date getCurrentDate() {
  return new Date(currentDate.getTime());
 }

}



package com.beingjavaguys.com;

import java.util.Date;

public class ImmutableDemo {

 /**
  * @Author Nagesh Chauhan
  */
 public static void main(String[] args) {
  /*
   * getting an instance of immutable class
   */
  IAmImmutable iAmImmutable = IAmImmutable.getInstance(2, "Andrew",
    new Date());
  System.out.println("Id: " + iAmImmutable.getId() + " Name: "
    + iAmImmutable.getName() + " Date:"
    + iAmImmutable.getCurrentDate());

  /*
   * Try to modify object's states
   */
  // iAmImmutable.getId() = 5; not permitted
  // iAmImmutable.getName() = "Stuart" not permitted
  iAmImmutable.getCurrentDate().setDate(23);
  /*
   * Printing values again to test
   */
  System.out.println("Id: " + iAmImmutable.getId() + " Name: "
    + iAmImmutable.getName() + " Date:"
    + iAmImmutable.getCurrentDate());
 }

}



Benefits of making a class Immutable

1) Thread-safe hence can be used in concurrent environment without synchronization.
2) Immutable objcts can be used to boost memory, we can simply save them and serve again and again.


That’s all about immutable classes and objects in java, we cam across what is immutablity ? What are immutable classes in Java ?, How to create a class immutable in Java ? and benefits of immutable classes in Java. In upcoming blogs we will see more about Java and Other opensource technologies.








Thanks for reading !
Being Java Guys Team




2 comments:

  1. Head First Design Patterns

    ReplyDelete
  2. in your first class why do we have to create an object

    /* this hold the logic of object creation, only point to get an object */

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft