静态控制流识别静态成员,执行静态块,然后执行静态main方法。让我们看一个例子-
public class Demo{
static int a = 97;
public static void main(String[] args){
print();
System.out.println("The main method has completed executing");
}
static{
System.out.println(a);
print();
System.out.println("We are inside the first static block");
}
public static void print(){
System.out.println(b);
}
static{
System.out.println("We are inside the second static block");
}
static int b = 899;
}输出结果
97 0 We are inside the first static block We are inside the second static block 899 The main method has completed executing
名为Demo的类包含一个静态变量和一个主函数,在其中调用了'print'函数。另一个静态块打印先前定义的静态变量,然后再次调用“ print”功能。定义了另一个静态“打印”功能,该功能可打印另一个变量。定义了另一个静态块,它打印相关消息。在所有这些静态代码块的外部,定义了另一个静态整数。