Tuesday, September 18, 2012

What is Immutable Object? How to create Immutable Object?


What is Immutable Object?
Immutable Object means unchangeable object i.e.  State cann’t be changed once object has created.

How to create Immutable Object?

1. Don’t Provide Setters
Every object will have state and property. For state, we provide Mutators(Setters) and Accessors(Getters) in terms of property. Here, we won’t provide mutators to our object.

2. Don’t allow subclasses to override methods.
There is a chance to change the functionality by overriding the methods. So it is betters make  methods as final or directly you can make the class as final.

3. Make all fileds final and private.
If fields not private, fields may be changed by direct assignment and make them final to guarantee that, value will not be changed.

4. Don’t allow mutable objects to be changed.
Yes, we can write mutable data types in our immutable class.  So, make a copy (clone or new) of mutable object when you are returning (in getters) or assigning (in constructors, methods) the data.

Here , I have Implemented the immutable class person.
Person.java:
//1. no setters in the class
//2. class is final
public final class Person {  
      //3. fields are private and final
      private final String name;
      private final StringBuilder about;
           
      public Person(String name, StringBuilder about){
            this.name = name;
            //4. assigning the copy
            this.about = new StringBuilder(about);
      }

      public String getName() {
            return name;
      }

      public StringBuilder getAbout() {
            //4. returning the copy
            return new StringBuilder(about);
      }    
}
ImmutablilityTest.java:
public class ImmutablilityTest {

      public static void main(String[] args) {       
            Person person1 = new Person("Leninkumar Koppoju", new StringBuilder("He is software engineer."));
            //Data before operations.
            System.out.println(person1.getName());
            System.out.println(person1.getAbout());
            //Adding the data
            person1.getName().concat(" Mr.");
            person1.getAbout().append("Added extra stuff to about.");
            //Data after operations.
            System.out.println(person1.getName());
            System.out.println(person1.getAbout());
      }
}

No comments:

Post a Comment