class Test{
static int x=10;
int y=99;
{
y=y+10;
}
static {
x=x+5;
}
{
y=y+10;
}
static {
x=x+5;
}
public Test() {//构造方法
x=x+5;
}
{
System.out.println(x*y);
}
}
public class a {
public static void main(String[] args) {
Test t1=new Test();
Test t2=new Test();
}
}
输出结果
2380
2975
调用构造方法前先从上向下执行代码块。静态代码块仅仅加载一次,普通代码块的执行次数与调用构造方法的次数相同。
t1
x是静态成员变量,加载一次static,x=15
在Text()中x=20
y为普通,为119
20x119=2380
t2
x(此时x=15)是静态成员变量,加载一次static,x=20
在Text()中x=25
y为普通,为119
25x119=2975