Searching...
Tuesday, July 15, 2014

How to create immutable classes in java

July 15, 2014
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 java9r.blogspot.com;

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 PersonDetails {
public static void main(String[] args) {
Person p = new Person(22, "ravi");
System.out.println(p.age);
System.out.println(p.name);
}
}


OutPut 

0 comments:

Post a Comment

ads2