Why final instance class variable in Java?

后端 未结 11 742
南方客
南方客 2020-12-09 05:13

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; 
         


        
11条回答
  •  隐瞒了意图╮
    2020-12-09 05:37

    You can't change the Basket. Still you can change the fruits inside.

    From Language specification # chapter 14.12.4

    Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

    When you declare a field or reference final, you must set the value once by the time the constructor exits.

    You can assign a value to that variable only in constructor.

     private  final Map CacheMap = new HashMap();
    

    here you can do

    CacheMap.put(.....  
    

    with in the class.

    but you cannot do

    CacheMap =   something.  //compile error.
    

    You should know the difference between value and reference.

    Edit

    Here

     Map cachemapdeclaredasfinal = cc.geConditionMap();
    
     Map newMap = new HashMap();
    
     cachemapdeclaredasfinal  = newMap; // In this case no error is shown
    

    Reason ,

    Since cachemapdeclaredasfinal is not a new map it's another reference of conditionMap

    when you create a new instance like this

       Map cachemapdeclaredasfinal =
                                    new HashMap(cc.geConditionMap());
    

    That error disappears. since you used new.

    Edit 2 :

     private Map conditionMap;
    
     public void setConditionMap(Map ConditionMap) {
            this.conditionMap = conditionMap;
        }
      private  final Map CacheMap = new HashMap();
      CacheDto cc = new CacheDto();
      cc.setConditionMap(CacheMap);
      Map cachemapdeclaredasfinal = cc.geConditionMap();
      Map newMap = new HashMap();
     cachemapdeclaredasfinal  = newMap;
    

    Here you what you confused is.

    You are assigning one final declared map to some normal(non final) map. When you retrieved that normal only you are getting and that not final so you can use/assign it further.

    In Short

    normalMap= finalMap; //no error since normalMap is not final
    finalMap =normalMap;// compiler error since normalMap is final
    

提交回复
热议问题