Saturday 25 February 2012

How to create immutable classes in java


Immutable class is the class whose value cannot be changed throughout the life cycle.
Ex:String
We cannot change the content of String class, everytime new reference is created when we change the content.

To create custom immutable  class in java
  1. Class should be made final so that no class can extend it. 
  2. Declare all variables as final
  3. Provide constructors to set the values
  4.  There should not be any public set method which can change the state of 
    the object.
  5. provde getter method




package com.usr.general;

final class Person {
       final int age;
       final String name;

       public Person(int age, String name) {
              this.age = age;
              this.name = name;

       }

       public int getAge() {
              return age;
       }

       public String getName() {
              return name;
       }
}

public class ImmutableDemo {
       public static void main(String[] args) {
              Person p = new Person(38, "sachin");
              System.out.println(p.age);
              System.out.println(p.name);
       }
}

OUTPUT
38
sachin