- 上代码:
public class TestDemo {
public static int[] statiArray;
public int[] array = {0,1,2,3};
public int int8 = 4;
// public static int staticInt;//0
public static int staticInt = 4;
static {
statiArray = new int[]{0,1,2,3};
/*
两句都在staticInt = 2
只有第一句staticInt = 1
只有第二句staticInt = 5
*/
staticInt = 1;
// staticInt += 1;
System.out.println("statiArray:"+statiArray[2]);
statiArray[2] = staticInt;//在最后声明编译报错,不能访问
System.out.println("statiArray:"+statiArray[2]);
System.out.println("staticInt:"+staticInt);//在最后声明编译报错,不能访问
}
public static void main(String[] args){
System.out.println("Test");
System.out.println("staticInt:"+staticInt);
}
// public static int staticInt = 4;//在最后声明编译不通过
}
运行结果:
- 再次上代码:
// staticInt = 1;
staticInt += 1;
运行结果:
- 问题:
数组是引用数据类型,随赋值而变,没什么好说的,但是 静态变量 之于 静态代码块 的 声明位置 可以直接影响编译是否通过就很有意思了~~~
而且 静态代码块 对 静态变量 的 二次赋值 和 二次运算赋值 结果不同,也是很有意思的~~~
(静态代码块 对 静态变量 的 二次赋值 会覆盖 之前 静态变量声明的初始值,二次运算赋值 则会以之前声明的值为基础)
初始化:
初始化是执行类构造器 <client>()方法 的过程:
1、<client>()方法 是由编译器自动收集类中所有类变量的赋值动作和静态语句块中的语句合并产生的,编译器收集的顺序是由语句在源文件中出现的顺序所决定的,静态语句块中只能访问到定义在静态语句块之前的变量,定义在它之后的变量,在前面静态语句块中可以赋值,但是不能访问。
2、<client>()方法 与类的构造函数(实力构造器<init>()方法)不同,它不需要显式地调用父类构造器,虚拟机会保证在子类的 <client>()方法 执行之前,父类的 <client>()方法 已经执行完毕。