Home > Java > javaTutorial > How to operate static initialization blocks in JAVA development

How to operate static initialization blocks in JAVA development

无忌哥哥
Release: 2018-07-20 10:18:57
Original
1520 people have browsed it

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();
        
	}
}
Copy after login

Running result:

通过静态初始化块初始化age
通过初始化块初始化sex
通过构造方法初始化name
姓名:tom,性别:男,年龄:20
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template