JVM如何初始化一个类
初始化一个类
经典案例
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
public static int x = 0;
public static int y;
private Singleton() {
x++;
y++;
}
public static void main(String[] args) {
Singleton singleton = getInstance();
System.out.println(x); // 0
System.out.println(y); // 1
}
}
public class Singleton2 {
public static int x = 0;
public static int y;
private static Singleton2 instance = new Singleton2();
public static Singleton2 getInstance() {
return instance;
}
private Singleton2() {
x++;
y++;
}
public static void main(String[] args) {
Singleton2 singleton = getInstance();
System.out.println(x); // 1
System.out.println(y); // 1
}
}
【勤则百弊皆除】