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

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

    This is possible due to the way in which the JVM works internally and the way Java was designed.

    After your code is compiled, the .class file generated will contain the bytecode representation of your code. A Class file is nothing but a bunch of bytes structured in a defined order which can be interpreted by the JVM.

    In a Class File structure you will be able to find something called the Constant Pool, which is nothing but a symbolic reference table used by the JVM when classes are loaded. Your final variables will be found here whether they are initialized or not as a literal.

    So now that you know this, let's move on and think of what the final modifier means, it means nothing but a way of telling the JVM that in this case a variable will be assigned a value and once this is done, a re-assignment operation on that variable will not be permitted, so as the Java Language documentation states, a final variable can be assigned a value once and only once.

    Now that you have this background, in order to answer your question directly:

    Whether your variable is an object or a primitive type, the value to a final variable which is not a class member (meaning is not static) will be automatically set by the JVM using the value in the runtime constant pool for your object OR if this variable is not initialized on declaration, then it will be required to be set when the constructor runs. All of this is possible because Java was designed this way to provide programmers some flexibility on variable assignment to avoid hard-coding and to provide a way to assign objects to final references.

    Just as a final tip, stop thinking as final variables as constants in C++. They might seem similar but they are not, they are handled in completely different ways.

提交回复
热议问题