Wednesday, July 22, 2015

How to create an Immutable class in JAVA

1) Make class as Final.
2) Private and Final variables.
3) No setter methods.
4) Values should be set only via public constructor.


public final class Contacts
{
   private final String name;
   private final String mobile;

   public Contacts (String name , String mobile)
   {
      this.name=name;
      this.mobile=mobile;
    } 

    public String getName()
    {
       return name;
    }

    public String getMobile()
    {
        return mobile;
     }
  }


Benefits of immutable classes in JAVA.

1) Immutable classes are by default thread-safe.

2) Immutable objects boost performance of Java application by reducing synchronization in code.

3) Reusability - You can cache immutable objects and reuse them much like string literals and 
    integers.
                You can use static factory methods to provide methods like valueOf(), which can return an existing immutable object from cache, instead of creating a new one.

 

No comments:

Post a Comment

Home