[英]Why final can be initialized in constructor?
I read 2 things 我读了两件事
final
should be intialized during declaration final
应该在声明期间初始化 blank final variable
which should be assigned at last line in constructor blank final variable
,应在构造函数的最后一行分配 Otherwise, you will get CTE
. 否则,您将获得
CTE
。
My question is, 我的问题是
Why Java allows to assign/initialize value of final in constructor?
为什么Java允许在构造函数中赋值/初始化final的值?
Because each instance can have it's own final
value for it. 因为每个实例都可以拥有自己的
final
值。 And that can be done only through constructor because you can call constructor only once. 那只能通过构造函数来完成,因为您只能调用一次构造函数。 If you want to make sure that the block gets executed only once and that too while creating the instance, constructor is the only place.
如果要确保该块仅执行一次,并且在创建实例时也要执行一次,则构造函数是唯一的位置。
If you hard code in the class ( initialising while declaring ), that will be same for all the instances and almost become static. 如果您在类中进行硬编码( 在声明时进行初始化 ),则所有实例都将相同,并且几乎变为静态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.