Sunday, 17 September 2017

Static Block in Java





I was looking over some code the other day and I came across:



static {
...
}


Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?


Answer



It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).




It can be thought of as a "class constructor".



Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...