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

前端 未结 8 766
夕颜
夕颜 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:00

    You must initialize a final variable once and only once. There are three ways to do that for an instance variable:

    1. in the constructor
    2. in an instance initialization block.
    3. when you declare it

    Here is an example of all three:

    public class X
    {
        private final int a;
        private final int b;
        private final int c = 10;
    
        {
           b = 20;
        }
    
        public X(final int val)
        {
            a = val;
        }
    }
    

    In each case the code is run once when you call new X(...) and there is no way to call any of those again, which satisfies the requirement of the initialization happening once and only once per instance.

提交回复
热议问题