Search code examples
javaobjectconstructorfinalcompile-time

Why final can be initialized in constructor?


I read 2 things

  1. final should be intialized during declaration
  2. Else it will be considered as blank final variable which should be assigned at last line in constructor

Otherwise, you will get CTE.

My question is,

Why Java allows to assign/initialize value of final in constructor?


Solution

  • Because each instance can have it's own final value for it. 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.