Home >Java >javaTutorial >How to operate static initialization blocks in JAVA development
The initialization block modified with static is called a static initialization block.
Special attention needs to be paid: The static initialization block is only executed when the class is loaded, and will only be executed once. At the same time, the static initialization block can only assign values to static variables and cannot initialize ordinary member variables.
Look at a piece of code:
public class HelloWorld { String name; // 声明变量name String sex; // 声明变量sex static int age;// 声明静态变量age // 构造方法 public HelloWorld () { System.out.println("通过构造方法初始化name"); name = "tom"; } // 初始化块 { System.out.println("通过初始化块初始化sex"); sex = "男"; } // 静态初始化块 static { System.out.println("通过静态初始化块初始化age"); age = 20; } public void show() { System.out.println("姓名:" + name + ",性别:" + sex + ",年龄:" + age); } public static void main(String[] args) { // 创建对象 HelloWorld hello = new HelloWorld(); // 调用对象的show方法 hello.show(); } }
Running result:
通过静态初始化块初始化age 通过初始化块初始化sex 通过构造方法初始化name 姓名:tom,性别:男,年龄:20
Because the static initialization block is executed when the class is loaded, the output in the static initialization block is output first. content. Then the normal initialization block is executed, and finally the constructor method is executed. Since the static initialization block is only executed when the class is loaded and is only executed once , the static initialization block is not executed when the object hello2 is created again.
The above is the detailed content of How to operate static initialization blocks in JAVA development. For more information, please follow other related articles on the PHP Chinese website!