- The role of the code block: used to initialize classes, objects
- If the code block is modified, only static can be used.
- Classification: static code block and non-static code block
1. Static code block
- There can be output statements inside
- Executed as the class is loaded, and only once
- Role: initialize the information of the class
- If multiple static code blocks are defined in a class, they are executed in the order of declaration
- The execution of static code blocks takes precedence over the execution of non-static code blocks
- Only static properties and static methods can be called in static code blocks, and non-static structures cannot be called
2. Non-static code block
- There can be output statements inside
- Execute as the object is created
- Every time an object is created, a non-static code block is executed
- Function: When creating an object, initialize the properties of the object, etc.
- If multiple non-static code blocks are defined in a class, they are executed in the order of declaration
- Non-static code blocks can call static properties, static methods, or non-static properties, non-static methods
3. Code example
/**
* @Author: YuShiwen
* @Date: 2020/11/17 3:51 PM
* @Version: 1.0
*/
public class BlockTest {
public static void main(String[] args) {
System.out.println("main方法中输出语句:"+Student.school);
Student student1 = new Student();
Student student2 = new Student();
System.out.println("main方法中输出语句:"+Student.school);
}
}
class Student{
String name;
int age;
static String school = "Yangtze University";
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//静态代码块
static {
System.out.println("static block1");
}
static {
System.out.println("static block2");
school = "Yangtze University !!!";
hobby();
//静态代码块中不可以调用非静态结果
//study();
}
//非静态代码块
{
System.out.println("block1");
}
{
System.out.println("block2");
//调用非静态结构
name = "YuShiwen";
age = 21;
study();
//调用静态结构
school = "~~ Yangtze University ~~";
hobby();
}
//方法
public void study(){
System.out.println("我是一个爱学习的人!");
}
public static void hobby(){
System.out.println("我喜欢健身!");
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Output result:
static block1
static block2
我喜欢健身!
main方法中输出语句:Yangtze University !!!
block1
block2
我是一个爱学习的人!
我喜欢健身!
block1
block2
我是一个爱学习的人!
我喜欢健身!
main方法中输出语句:~~ Yangtze University ~~
Process finished with exit code 0
Sample code analysis: