Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why Static initializer blck use / need??  RSS feed

 
Vijay Rathi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Please tell me Why Static initializer blocks are used??

Thanks

rathi.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a static method uses a static variable you can use the static block to initialize the variable before anyone calls the method the first time. That's about all I've ever used a static block for.
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that a static initialization block may need to exist so that the static fields that it initializes are initialized to something other than the default fields (zero-filled).

A static field may be accessed before any object of that class is instantiated so you can't do the static initialization in any constructor.

For example,

Math.pi

has the right value even though there is no object of the class Math.

-- Kaydell
 
Jeroen T Wenting
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yup, that's the main reason.
It also prevents code in constructors that should only be used once (during class loading) to initialise static data members (otherwise you'd need a lot of "if xxx != null // ..." stuff in your constructors.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!