class B
{
public static B t1 = new B();
public static B t2 = new B();
static
{
System.out.println("静态块");
}
{
System.out.println("构造块");
}
}
public class Constract{
public static void main(String[] args)
{
B t = new B();
}
}
输出结果
构造块
构造块
静态块
构造块
接下来解析以下为什么会出现这种结果:
静态变量和静态代码块中的语句会汇集到类构造函数中运行
首先t1,t2是静态变量,
public static B t1 = new B();
public static B t2 = new B();
所以实际执行是(
public static B t1;
public static B t2;
pubic staic B{
t1 = new B();
t2 = new B();
System.out.println("静态块");
}
首先要执行t1,t2的实例化,所以先输出 构造块
静态代码块中的语句和静态变量的初始化顺序于代码的顺序有关:
如果是
static
{
System.out.println("静态块");
}
public static B t1 = new B();
public static B t2 = new B();
那么,代码最终执行是
public static B t1;
public static B t2;
pubic staic B{
System.out.println("静态块");
t1 = new B();
t2 = new B();
}
会先输出 静态块