类的加载过程

一: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值