一:public class jiazai {
public static void main(String[] args) {
c c = new c();
System.out.println(c.x);
}
}
class b{
static int a=5;
static {
a+=5;
System.out.println(“我是爸爸”+a);
}
public b() {
System.out.println(“我是爸爸构造方法”);
}
{
System.out.println(“我是爸爸构造代码块”);
}
}
class c extends b{
static int x=1;
static {
System.out.println(“我是儿子静态”);
}
二:
public class ClassInit {
static{
try {
System.out.println(“这是静态语句块,我被初始化了”);
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
IntStream.range(0,5).forEach(i->new Thread(ClassInit :: new));
}
}
三:
public class Singleton {
//(1)
private static int x = 0;
private static int y ;
private static Singleton singleton = new Singleton();//(2)
private Singleton(){
x++;
y++;
}
public static Singleton getSingleton(){
return singleton;
}
public static void main(String[] args) {
Singleton singleton = Singleton.getSingleton();
System.out.println("这是X变量"+singleton.x);
System.out.println("这是Y变量"+singleton.y);
}
}
当(2)语句放到(1)位置时,输出的结果会有变化,目前这个代码输出结果会是:X=1,Y=1。当语句变动后,输出结果为:X=0,Y=1。解释一下:
private static int x = 0;
private static int y ;
private static Singleton singleton = new Singleton();
在连接阶段的准备过程中,每个变量都会被赋一个初始值 x=0 y=0 singleton = null,跳过解析过程,在初始化阶段每一个变量赋正确的值
x=0,y=0,singleton=new Singleton(),在new Singleton的时候执行类的构造函数,对x和y进行了自增,因此结果为x=1,y=1.
private static Singleton singleton = new Singleton();
private static int x = 0;
private static int y ;
在连接阶段的准备过程中,每个变量都会被赋一个初始值 singleton = null,x=0,y=0 跳过解析过程,在初始化阶段每一个变量赋正确的值,首先会进入Singleton的构造函数,执行完构造函数后 x=1,y=1,然后开始初始化x,y, x被赋予0的值,y没有被赋值,因此在构造函数中的值即为y的值,y=1,所以结果为x=0,y=1