If instance variable is set final its value can not be changed like
public class Final {
private final int b;
Final(int b) {
this.b = b;
}
int getFinal() {
return b = 8; // COMPILE TIME ERROR
}
}
Somewhere in code I have seen instance class variable HashMap declared as final
private final Map<String, Object> cacheMap = new HashMap<String, Object>();
I could not understand why it is declared so? Normally in which case it is declared. Does it mean if once I put in hash map then I could not change its value?
Edit:
If cacheMap which is declared as final is passed as parameter to another class then error is not shown for final if I change its reference. Why it is so?
class CacheDTO {
private Map conditionMap;
public Map getConditionMap() {
return conditionMap;
}
public void setConditionMap(Map conditionMap) {
this.conditionMap = conditionMap;
}
}
Then
private final Map<String, Object> cacheMap = new HashMap<String, Object>();
CacheDTO cc = new CacheDTO();
cc.setConditionMap(cacheMap);
Map<String, Object> cacheMapDeclaredAsFinal = cc.getConditionMap();
Map<String, Object> newMap = new HashMap<String, Object>();
cacheMapDeclaredAsFinal = newMap; // In this case no error is shown. Though cacheMapDeclaredAsFinal reference is obtained by calling cc.getConditionMap() and cacheMapDeclaredAsFinal refers to final.