简体   繁体   English

为什么final可以在构造函数中初始化?

[英]Why final can be initialized in constructor?

I read 2 things 我读了两件事

  1. final should be intialized during declaration final应该在声明期间初始化
  2. Else it will be considered as 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.

相关问题 必须在构造函数完成之前初始化最终参考变量? 为什么? - final reference variables must be initialized before constructor complete ? Why? 为什么必须在构造函数完成之前初始化最终变量? - Why must a final variable be initialized before constructor completes? 在Java中,可以从构造函数助手初始化final字段吗? - In Java, can a final field be initialized from a constructor helper? java 子类的私有 final 字段可以在超级构造函数完成之前初始化吗? - Can a java subclass's private final field be initialized before the super constructor completes? 如果最终变量在参数化构造函数中动态初始化,则它违反最终规则 - If final variable is initialized in parameterized constructor dynamically, then it breaks final rule 确保在构造函数抛出异常时初始化最终变量 - Making sure that a final variable is initialized when a constructor throws an exception 使用 super() 构造函数时,未初始化空白最终字段 - Blank final fields are not initialized when using a super()-constructor Java 并发:final 字段(在构造函数中初始化)是线程安全的吗? - Java concurrency: is final field (initialized in constructor) thread-safe? 如何使用 EasyMock 和 PowerMock 模拟构造函数内部初始化的最终变量? - How to mock final variable initialized inside constructor ,using EasyMock and PowerMock? 创建对象时可以初始化最终变量吗? - Can a final variable be initialized when an object is created?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM