Java tutorial "Initialize Fields" (https://docs.oracle.com/javase/tutorial/java/javaOO/initial) published at https://docs.oracle.com/en/java/ .html) A brief note about "Static Initialization Blocks" that was often asked at https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html. (Detailed commentary may be written if you feel like it)
You can write a block using static {....}
and put the static field initialization there. This is called Static Initialization Blocks.
The Static Initialization Block is a block that is executed before the constructor.
The Static Initialization Block is not yet executed when the class is just used in the declaration.
The Static Initialization Block is executed first when the constructor or static method of the class is called.
{....}
without static becomes Blocks (Initialization Blocks) for initialization of instance fields. This is also executed before the constructor.
The logic in Initialization Blocks is called from any constructor, so if there is a constructor overload, you can put in logic that does the same for any constructor.
InitializationBlocksSample.java
public class InitializationBlocksSample {
final static int x;
int y;
// Static Initialization Blocks, it is called before first load.
static {
x=10;
System.out.println("Static Initialization Blocks");
}
// Initialization Blocks, it it called from all constructors.
{
y=10;
System.out.println("Initialization Blocks");
}
// constructor
public InitializationBlocksSample() {
System.out.println("non-parameter constructor");
}
public InitializationBlocksSample(String param) {
System.out.println("parameter constructor");
}
public static void staticMethod() {
System.out.println("staticMethod");
}
public void instanceMethod() {
System.out.println("instanceMethod");
}
}
Main.java
public class Main {
public static void main(String[] args) {
InitializationBlocksSample o;
System.out.println("start");
InitializationBlocksSample.staticMethod();
o = new InitializationBlocksSample();
o.instanceMethod();
InitializationBlocksSample p = new InitializationBlocksSample("parameter");
}
}
Static related articles: [Java static story](https://qiita.com/b1ueskydragon/items/2a6e0812a9cee3fc255f#static-%E3%82%A4%E3%83%8B%E3%82%B7%E3% 83% A3% E3% 83% A9% E3% 82% A4% E3% 82% B6)
Recommended Posts