0
Sponsored Links


Ad by Google
Immutable very hot topic in java interview, few java interview questions are always on demand like Design your own ArrayList , How Many Ways to iterate HashMap , Serializable Vs Externalizable , What are the key differences between Comparable and Comparator , Why hash code method in java.

OK, Let's start our main topic How to create Immutable class, In this post we are going to show you a sample program to create immutable class. There are lot of immutable classes in java and few them are listed here java immutable classes
What is Immutable: Immutable means once the constructor of an object is completed the execution, that instance can't be change using public api of the class. Or you can say object is an immutable if it's state can't be change after it's construction like java.lang.String
Why Immutable: Immutable objects are safe to share between multiple threads, because instances of immutable classes never change after construction. So immutable object are automatically thread safe no requirement of synchronization. Here you can read more Why String is immutable.

Below are the few key rules needs to keep in mind while creating Immutable Class in java.
  • Rule # 1. Make the class final.
  • Rule # 2. Make all fields final and private.
  • Rule # 3. No method that modify the state of the object (Don't provide "setter" methods).
  • Rule # 4. Don't provides method to modify mutable objects.
  • Rule # 5. Do defensive programming for mutable objects, Because possible some property may be final but the object can still be mutable. example private final Date imMutable.

OK. Let's implement all the above rules to create our own immutable object. Be careful while creating immutable class, if you missed any of the above rule, will definitely caused the broken immutability.
Here is a mutable class Contact.java we are going to use this mutable class as references variable in our Person.java which is our immutable class.

package com.javamakeuse.poc;

public class Contact implements Cloneable {
 private String emailId;
 private String mobile;

 public String getEmailId() {
  return emailId;
 }
 public void setEmailId(String emailId) {
  this.emailId = emailId;
 }
 public String getMobile() {
  return mobile;
 }
 public void setMobile(String mobile) {
  this.mobile = mobile;
 }
 public Contact() {
 }
 public Contact(String emailId, String mobile) {
  super();
  this.emailId = emailId;
  this.mobile = mobile;
 }
 @Override
 public String toString() {
  return "Contact [emailId=" + emailId + ", mobile=" + mobile + "]";
 }
 public Object clone() {
  Contact contact = null;
  try {
   contact = (Contact) super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }
  return contact;
 }

}
And now our immutable class Person.java

package com.javamakeuse.poc;

public final class Person {
 private final int id;
 private final Contact contact;

 public Person(int id, Contact contact) {
  super();
  this.id = id;
  this.contact = new Contact(contact.getEmailId(), contact.getMobile());
 }
 public int getId() {
  return id;
 }
 public Contact getContact() {
  return (Contact) contact.clone();//here defensive copies of mutable field
 }
 @Override
 public String toString() {
  return "Person [id=" + id + ", contact=" + contact + "]";
 }

}

Lets test our immutable class in TestImmutablity.java
package com.javamakeuse.poc;

public class TestImmutablity {
public static void main(String[] args) {
 
 Contact contact = new Contact();
 contact.setEmailId("info@javamkeuse.com");
 contact.setMobile("9953527080");
 Person person = new Person(1, contact);
 
 // Lets try to break it by setting the new values.
 person.getContact().setEmailId("info@mymail.com");
 person.getContact().setMobile("9090909090");
 
 // printing the person object.
 System.out.println(person);
}
}

We have successfully implemented all the above rules, So our object is completely immutable.
OUT PUT:
Person [id=1, contact=Contact [emailId=info@javamkeuse.com, mobile=9953527080]]

If you would like to test all the rules, you can start with removing clone method, instead of returning clone object you can return original object and run the same program, and see the out put it will print emailId as "info@mymail.com" and also mobile no as "9090909090" because returning original object from the getContact() method will break your immutability.

That's it very simple and to the point, Of course you can download this project from MyImmutable Project.
Definitely I will appreciate a lot if you can post your comment/feedback or any point if i missed.

Few interesting posts:
Which Collection is better to store 10 millions of records between ArrayList and LinkedList
How many ways to create object in java
Java Program to find missing number from an array
Create your own generator class in hibernate
Sponsored Links

0 comments:

Post a Comment