Can a final variable be initialized when an object is created?

前端 未结 8 746
夕颜
夕颜 2020-12-09 10:29

how it can be possible that we can initialize the final variable of the class at the creation time of the object ?

Anybody can explain it how is it possible ? ...<

相关标签:
8条回答
  • 2020-12-09 11:08

    If you mean a static final member you can use a static initializer:

    class Example {
      public final static Map<String,Object> C;
    
      static {
        C = new HashMap<>();
        C.put("hi", 5);
      }
    }
    
    0 讨论(0)
  • 2020-12-09 11:21

    A final value is one which can only be set once, and only in the constructor. There is no reason it cannot be set by the constructor to any value you like.

    If you had a value which you wanted to be a constant for all instance, you would make it static final and you would NOT be able to set it in a constructor. Perhaps you are confusing the two.

    0 讨论(0)
提交回复
热议问题