Java allows you to use the so called “init blocks”. You can declare static and instance init blocks. The static init blocks will run exactly once, when the ClassLoader loads the class that declares it, and the instance init blocks run everytime you construct a new object, after the actual constructor ran.
The general order of execution is like this:
- Once the class gets loaded by the ClassLoader, it runs every
static init block
once, in the order of their declaration - When you construct a new instance using the constructor, it first runs the constructor’s code, followed by every
init block
in the order of their declaration
Here’s a small example class:
public class Test { static { System.out.println("This is the static init block. All the code here runs once when you the ClassLoader loads the class."); } { System.out.println("This is an instance init block. It gets called every time you create a new instance of this class, AFTER the normal constructor's code ran."); } static { System.out.println("This is another static init block."); printSomething(); } { System.out.println("This is another instance init block."); } public Test() { System.out.println("This is a no-args constructor."); } public Test(String anUnusedString) { System.out.println("This is a constructor with a String parameter."); printSomething(); } public static void printSomething() { System.out.println("I am printing something."); } }
How let’s imagine that we have another class that simply constructs a few instances of the above class:
public class TestE { public static void main(String[] args) { new Test(); new Test("someString"); new Test(); } }
If you would now run TestE.main(String…), you’d get the following output:
This is the static init block. All the code here runs once when you the ClassLoader loads the class. This is another static init block. I am printing something. This is an instance init block. It gets called every time you create a new instance of this class, AFTER the normal constructor's code ran. This is another instance init block. This is a no-args constructor. This is an instance init block. It gets called every time you create a new instance of this class, AFTER the normal constructor's code ran. This is another instance init block. This is a constructor with a String parameter. I am printing something. This is an instance init block. It gets called every time you create a new instance of this class, AFTER the normal constructor's code ran. This is another instance init block. This is a no-args constructor.
Join my Discord Server for feedback or support. Just check out the channel #programming-help
🙂
I see the use of the static init blocks, but when might the instance ones be useful?
For example, if you have different constructors but you all want them to share a part of code.