• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final static and initializer compile error

 
yogesh doshi
Ranch Hand
Posts: 33
Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I declared variable as final static I am not allowed to initialize same inside Instance Initialize Block(IIB) nut when I just declared the varaible as final I am allowed. I am confused can anyone help me.



Below one is correct

 
Henry Wong
author
Marshal
Pie
Posts: 22094
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yogesh doshi wrote:When I declared variable as final static I am not allowed to initialize same inside Instance Initialize Block(IIB) nut when I just declared the varaible as final I am allowed. I am confused can anyone help me.


Final static variables are initialized when the class is first loaded (and it must be initialized exactly once). The code that is ran (during class load) are the static initializer and the static variable initializer. Your first code example isn't a case of either of those two initialization options.

Final instance variables are initialized when an object is instantiated (and it must be initialized exactly once). The code that is ran (during instantiation) are the constructor, instance initializer, and the instance variable initializer. Your second code example is a case of using an instance initializer.

Henry
 
Henry Wong
author
Marshal
Pie
Posts: 22094
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

One other point... Yes, it is possible to initialize a static variable from an instance context. However, since it is impossible to guarantee that it is initialized exactly once (from that context), it is not allowed for final static variables.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic