Monday, June 29, 2015

Java Immutable Object

The simple definition of immutable object is "An object called immutable whose states can't be changed after it constructed". It means every time we need to alter the state we actually end up having a new object. The best example is "java.lang.String".

Some body might be thinking its actually overhead, this practice ends up creating too many objects. Actually over the time with optimization of garbage collection and the cost of creating new objects decreases. So in a situation where you want to define constant, or say a multi threading case immutable objects work well. As the value doesn't change at any stage, we are assured of dirty or inconsistent value.

Lets understand how to create our own immutable object.

1) Make the class final, to stop any other class to extend.
2) All fields in the class should be private and final.
3) Since we don't want the state of the object to change,  there should not be any setter method.
4) Any method which require to change the state, must create a new object with updated state.

For Ex:

final public class MyCar
     private final String registrationNumber;
     public MyCar(String registrationNumber)
        this.registrationNumber = registrationNumber;
     public String getRegistrationNumber()
        return registrationNumber;
    public MyCar upgradeCar(String newCarRegNo)
       return new MyCar(newCarRegNo);

1 comment:

  1. Wow, thanks for the 101 like that, Pallab! I'm a newbie in that whole topic, and posts like this one of yours help me to dig deeper in that) So, for now I wasn't even able to understand the logic of Java itself and it I'm not familiar with all the theory, even not talking about some practices to do.. But recently an experienced backender, who also is a friend of mine, had suggested me this courses in order to get to know Java basics at its best, like the whole logic of java string pool e.g. And it is working out perfectly for me! I guess I'm not so far from the moment where I would be able to understand aspects of working with objects for sure :)