,

Saturday 24 June 2017

Immutable class in java


Immutable class is one whose properties cannot be modified.
In other words, the state of objects of immutable class does not change after it is initialised.

To make a class immutable follow below mentioned steps.
1) Make the class final so that it cannot be extended.
2) Declare the variables as private and final.
3) Declare and define the getters for all variable and do not create the setters.
4) Create constructor with parameters.

Below is the example of Immutable class

package com.immutable;
/**
 * 
 * @author ganeshrashinker
 *
 */
//make the class final
public final class Employee {
//make the variables private and final
private final String name;
private final int age;
//define the getters for the private variables
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Employee(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + "]";
}

Class with main method

package com.immutable;
/**
 * 
 * @author ganeshrashinker
 *
 */

public class MainClass {

public static void main(String[] args) {
Employee employee = new Employee("Rahul", 55);
System.out.println(employee);
}

}

Output is: Employee [name=Rahul, age=55]

Note: Immutable classes are beneficial for Caching purpose and they are thread safe.

No comments:

Post a Comment