关于类加载的一道面试题

class Singleton{

private static Singleton singleton = new Singleton();

public static int counter;

public static int counter2 = 0;

private Singleton(){

counter1++;

counter2++;

}


public static Singleton getInstance(){

return singleton ;

}

}


public class Test{

public static void main(String[] args){

Singleton singleton = Singleton.getInstance();

System.out.println("counter1 = "+singleton.counter1 );

System.out.println("counter2 = "+singleton.counter2 );

}

}


Singleton singleton = Singleton.getInstance();这行代码首先给Singleton中的变量赋予默认的初始值:

即:private static Singleton singleton的singleton赋予默认初始值null、

public static int counter的counter1赋予默认初始值0、

public static int counter的counter2赋予默认初始值0(不是显式的0)、

然后会显式地给变量赋值:

private static Singleton singleton的singleton赋予new Singleton(),此时会执行Singleton类的构造函数:

private Singleton(){

counter1++;

counter2++;

}

counter1 = 1;

counter2 = 1;

接着给counet1、counter2显式赋值

public static int counter;

public static int counter2 = 0;

由于counter1没有显式值

所以赋值完成后counter1 = 1、counter2 = 0;

最后输出为counter1 = 1、counter2 = 0;



如果把 private static Singleton singleton = new Singleton();放在 public static int counter2 = 0;的后面,则会输出counter1 = 1、counter2 = 1;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值