Thursday, 23 May 2019

How to make Immutable class in java

Immutable Class in Java :-
String, Boolean, Byte, Short are immutable class in java.

Immutable class in java mean once object of class created ,than the state of object cannot be change.

Here are following steps to create the immutable class in java:-

1. create a class as final :- That no one can extends the class.

2. Declare the Variable as private that  direct access not allowed.

3. Declare the variable as final that value can assign only once.

4. No setter method allowed.

5. Only getter method  : Will have perform cloning of object in getter method to return rather than return actual object.

import java.util.HashMap;
import java.util.Map;

public final class ImmutableClass {

private final String name;
private final int id;
private final Map<Integer, Integer> map;

public ImmutableClass(String name, int id, Map<Integer, Integer> map) {
this.name = name;
this.id = id;
Map<Integer, Integer> tempMap = new HashMap<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
tempMap.put(entry.getKey(), entry.getValue());
}
this.map = tempMap;
}

public String getName() {
return name;
}

public int getId() {
return id;
}

public Map<Integer, Integer> getMap() {
Map<Integer, Integer> tempMap = new HashMap<>();
tempMap = map;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
tempMap.put(entry.getKey(), entry.getValue());
}
return tempMap;
}
}

No comments:

Post a Comment